summaryrefslogtreecommitdiff
path: root/zookeeper-server/src/test/java/org/apache/zookeeper/server
diff options
context:
space:
mode:
authortison <wander4096@gmail.com>2019-08-17 08:13:15 -0700
committerMichael Han <hanm@apache.org>2019-08-17 08:13:15 -0700
commitfe940cdd8fb23ba09684cefb73233d570f4a20fa (patch)
tree28de6768b6ef6f233840636cb50a1cd35512e319 /zookeeper-server/src/test/java/org/apache/zookeeper/server
parent04cc5cae1e7d4b007490e68109a676b88ce790a3 (diff)
downloadzookeeper-fe940cdd8fb23ba09684cefb73233d570f4a20fa.tar.gz
ZOOKEEPER-3475: Enable Checkstyle configuration on zookeeper-server
- [x] org/apache/zookeeper - [x] org/apache/zookeeper/admin - [x] org/apache/zookeeper/cli - [x] org/apache/zookeeper/client - [x] org/apache/zookeeper/common - [x] org/apache/zookeeper/jmx - [x] org/apache/zookeeper/metrics - [x] org/apache/zookeeper/metrics/impl - [x] org/apache/zookeeper/server - [x] org/apache/zookeeper/server/admin - [x] org/apache/zookeeper/server/auth - [x] org/apache/zookeeper/server/command - [x] org/apache/zookeeper/server/metric - [x] org/apache/zookeeper/server/persistence - [x] org/apache/zookeeper/server/quorum - [x] org/apache/zookeeper/server/quorum/auth - [x] org/apache/zookeeper/server/quorum/flexible - [x] org/apache/zookeeper/server/util - [x] org/apache/zookeeper/server/watch - [x] org/apache/zookeeper/test - [x] org/apache/zookeeper/util - [x] org/apache/zookeeper/version/util Author: tison <wander4096@gmail.com> Reviewers: Brian Nixon <nixon@fb.com>, Enrico Olivelli <eolivelli@gmail.com>, Michael Han <hanm@apache.org> Closes #1049 from TisonKun/ZOOKEEPER-3475
Diffstat (limited to 'zookeeper-server/src/test/java/org/apache/zookeeper/server')
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java62
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java70
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java69
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java174
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java129
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java220
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java34
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java35
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java51
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java37
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java17
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java4
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java13
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java48
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java94
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java36
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java92
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java104
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java173
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java32
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java71
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java57
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java35
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java39
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java49
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java70
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java12
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java14
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java359
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java107
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java17
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java13
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java161
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java130
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java94
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java46
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java442
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java43
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java117
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java28
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java259
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java390
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java204
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java222
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java6
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java102
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java95
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java44
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java33
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java45
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java124
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java46
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java44
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java100
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java68
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java43
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java51
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java82
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java5
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java38
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java852
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java135
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java87
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java386
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java62
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java168
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java114
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java269
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java92
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java6
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java102
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java96
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java66
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java107
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java161
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java53
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java750
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java58
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java16
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java82
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java102
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java57
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java78
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java97
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java28
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java74
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java41
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java26
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java26
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java397
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java143
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java69
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java34
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java14
127 files changed, 5496 insertions, 6032 deletions
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
index aa27a15f7..c3d10bb56 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,21 +15,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import java.util.Random;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Random;
-
public class BlueThrottleTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(BlueThrottleTest.class);
class MockRandom extends Random {
+
int flag = 0;
BlueThrottle throttle;
@@ -42,20 +45,23 @@ public class BlueThrottleTest extends ZKTestCase {
return 1;
}
}
+
}
class BlueThrottleWithMockRandom extends BlueThrottle {
+
public BlueThrottleWithMockRandom(MockRandom random) {
super();
this.rng = random;
random.throttle = this;
}
+
}
@Test
public void testThrottleDisabled() {
BlueThrottle throttler = new BlueThrottle();
- Assert.assertTrue("Throttle should be disabled by default", throttler.checkLimit(1));
+ assertTrue("Throttle should be disabled by default", throttler.checkLimit(1));
}
@Test
@@ -63,8 +69,8 @@ public class BlueThrottleTest extends ZKTestCase {
BlueThrottle throttler = new BlueThrottle();
throttler.setMaxTokens(1);
throttler.setFillTime(2000);
- Assert.assertTrue("First request should be allowed", throttler.checkLimit(1));
- Assert.assertFalse("Second request should be denied", throttler.checkLimit(1));
+ assertTrue("First request should be allowed", throttler.checkLimit(1));
+ assertFalse("Second request should be denied", throttler.checkLimit(1));
}
@Test
@@ -72,12 +78,12 @@ public class BlueThrottleTest extends ZKTestCase {
BlueThrottle throttler = new BlueThrottle();
throttler.setMaxTokens(1);
throttler.setFillTime(500);
- Assert.assertTrue("First request should be allowed", throttler.checkLimit(1));
- Assert.assertFalse("Second request should be denied", throttler.checkLimit(1));
+ assertTrue("First request should be allowed", throttler.checkLimit(1));
+ assertFalse("Second request should be denied", throttler.checkLimit(1));
//wait for the bucket to be refilled
Thread.sleep(750);
- Assert.assertTrue("Third request should be allowed since we've got a new token", throttler.checkLimit(1));
+ assertTrue("Third request should be allowed since we've got a new token", throttler.checkLimit(1));
}
@Test
@@ -88,24 +94,24 @@ public class BlueThrottleTest extends ZKTestCase {
throttler.setFillCount(maxTokens);
throttler.setFillTime(1000);
- for (int i=0;i<maxTokens;i++) {
+ for (int i = 0; i < maxTokens; i++) {
throttler.checkLimit(1);
}
- Assert.assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
+ assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
Thread.sleep(110);
throttler.checkLimit(1);
- Assert.assertFalse("Dropping probability should still be zero", throttler.getDropChance()>0);
+ assertFalse("Dropping probability should still be zero", throttler.getDropChance() > 0);
//allow bucket to be refilled
Thread.sleep(1500);
- for (int i=0;i<maxTokens;i++) {
- Assert.assertTrue("The first " + maxTokens + " requests should be allowed", throttler.checkLimit(1));
+ for (int i = 0; i < maxTokens; i++) {
+ assertTrue("The first " + maxTokens + " requests should be allowed", throttler.checkLimit(1));
}
- for (int i=0;i<maxTokens;i++) {
- Assert.assertFalse("The latter " + maxTokens + " requests should be denied", throttler.checkLimit(1));
+ for (int i = 0; i < maxTokens; i++) {
+ assertFalse("The latter " + maxTokens + " requests should be denied", throttler.checkLimit(1));
}
}
@@ -119,14 +125,15 @@ public class BlueThrottleTest extends ZKTestCase {
throttler.setFreezeTime(100);
throttler.setDropIncrease(0.5);
- for (int i=0;i<maxTokens;i++)
+ for (int i = 0; i < maxTokens; i++) {
throttler.checkLimit(1);
- Assert.assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
+ }
+ assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
Thread.sleep(120);
//this will trigger dropping probability being increased
throttler.checkLimit(1);
- Assert.assertTrue("Dropping probability should be increased", throttler.getDropChance()>0);
+ assertTrue("Dropping probability should be increased", throttler.getDropChance() > 0);
LOG.info("Dropping probability is {}", throttler.getDropChance());
//allow bucket to be refilled
@@ -134,24 +141,25 @@ public class BlueThrottleTest extends ZKTestCase {
LOG.info("Bucket is refilled with {} tokens.", maxTokens);
int accepted = 0;
- for (int i=0;i<maxTokens;i++) {
+ for (int i = 0; i < maxTokens; i++) {
if (throttler.checkLimit(1)) {
- accepted ++;
+ accepted++;
}
}
LOG.info("Send {} requests, {} are accepted", maxTokens, accepted);
- Assert.assertTrue("The dropping should be distributed", accepted<maxTokens);
+ assertTrue("The dropping should be distributed", accepted < maxTokens);
accepted = 0;
- for (int i=0;i<maxTokens;i++) {
+ for (int i = 0; i < maxTokens; i++) {
if (throttler.checkLimit(1)) {
- accepted ++;
+ accepted++;
}
}
LOG.info("Send another {} requests, {} are accepted", maxTokens, accepted);
- Assert.assertTrue("Later requests should have a chance", accepted > 0);
+ assertTrue("Later requests should have a chance", accepted > 0);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
index 80c20e1f8..7e8c3870e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,23 +15,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import static org.junit.Assert.*;
public class ByteBufferInputStreamTest extends ZKTestCase {
- private static final byte[] DATA_BYTES_0 =
- "Apache ZooKeeper".getBytes(Charset.forName("UTF-8"));
+
+ private static final byte[] DATA_BYTES_0 = "Apache ZooKeeper".getBytes(StandardCharsets.UTF_8);
private static byte[] DATA_BYTES;
- @BeforeClass public static void setUpClass() {
+ @BeforeClass
+ public static void setUpClass() {
int len = DATA_BYTES_0.length + 2;
DATA_BYTES = new byte[len];
System.arraycopy(DATA_BYTES_0, 0, DATA_BYTES, 0, DATA_BYTES_0.length);
@@ -42,42 +45,42 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
private ByteBuffer bb;
private ByteBufferInputStream in;
private byte[] bs;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
bb = ByteBuffer.wrap(DATA_BYTES);
in = new ByteBufferInputStream(bb);
- bs = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
+ bs = new byte[]{(byte) 1, (byte) 2, (byte) 3, (byte) 4};
}
- @Test public void testRead() throws Exception {
+ @Test
+ public void testRead() throws Exception {
for (int i = 0; i < DATA_BYTES.length; i++) {
int b = in.read();
assertEquals(DATA_BYTES[i], (byte) b);
}
assertEquals(-1, in.read());
}
- @Test public void testReadArrayOffsetLength() throws Exception {
+ @Test
+ public void testReadArrayOffsetLength() throws Exception {
assertEquals(1, in.read(bs, 2, 1));
- byte[] expected =
- new byte[] { (byte) 1, (byte) 2, DATA_BYTES[0], (byte) 4 };
+ byte[] expected = new byte[]{(byte) 1, (byte) 2, DATA_BYTES[0], (byte) 4};
assertArrayEquals(expected, bs);
}
- @Test(expected=IndexOutOfBoundsException.class)
+ @Test(expected = IndexOutOfBoundsException.class)
public void testReadArrayOffsetLength_LengthTooLarge() throws Exception {
in.read(bs, 2, 3);
}
- @Test public void testReadArrayOffsetLength_HitEndOfStream()
- throws Exception {
+ @Test
+ public void testReadArrayOffsetLength_HitEndOfStream() throws Exception {
for (int i = 0; i < DATA_BYTES.length - 1; i++) {
in.read();
}
assertEquals(1, in.read(bs, 2, 2));
- byte[] expected =
- new byte[] { (byte) 1, (byte) 2, DATA_BYTES[DATA_BYTES.length - 1],
- (byte) 4 };
+ byte[] expected = new byte[]{(byte) 1, (byte) 2, DATA_BYTES[DATA_BYTES.length - 1], (byte) 4};
assertArrayEquals(expected, bs);
}
- @Test public void testReadArrayOffsetLength_AtEndOfStream()
- throws Exception {
+ @Test
+ public void testReadArrayOffsetLength_AtEndOfStream() throws Exception {
for (int i = 0; i < DATA_BYTES.length; i++) {
in.read();
}
@@ -85,24 +88,28 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
assertEquals(-1, in.read(bs, 2, 2));
assertArrayEquals(expected, bs);
}
- @Test public void testReadArrayOffsetLength_0Length() throws Exception {
+ @Test
+ public void testReadArrayOffsetLength_0Length() throws Exception {
byte[] expected = Arrays.copyOf(bs, bs.length);
assertEquals(0, in.read(bs, 2, 0));
assertArrayEquals(expected, bs);
}
- @Test public void testReadArray() throws Exception {
+ @Test
+ public void testReadArray() throws Exception {
byte[] expected = Arrays.copyOf(DATA_BYTES, 4);
assertEquals(4, in.read(bs));
assertArrayEquals(expected, bs);
}
- @Test public void testSkip() throws Exception {
+ @Test
+ public void testSkip() throws Exception {
in.read();
assertEquals(2L, in.skip(2L));
assertEquals(DATA_BYTES[3], in.read());
assertEquals(DATA_BYTES[4], in.read());
}
- @Test public void testSkip2() throws Exception {
+ @Test
+ public void testSkip2() throws Exception {
for (int i = 0; i < DATA_BYTES.length / 2; i++) {
in.read();
}
@@ -112,20 +119,23 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
assertEquals(DATA_BYTES[idx++], in.read());
assertEquals(DATA_BYTES[idx++], in.read());
}
- @Test public void testNegativeSkip() throws Exception {
+ @Test
+ public void testNegativeSkip() throws Exception {
in.read();
assertEquals(0L, in.skip(-2L));
assertEquals(DATA_BYTES[1], in.read());
assertEquals(DATA_BYTES[2], in.read());
}
- @Test public void testSkip_HitEnd() throws Exception {
- for (int i = 0; i < DATA_BYTES.length - 1; i++) {
+ @Test
+ public void testSkip_HitEnd() throws Exception {
+ for (int i = 0; i < DATA_BYTES.length - 1; i++) {
in.read();
}
assertEquals(1L, in.skip(2L));
assertEquals(-1, in.read());
}
- @Test public void testSkip_AtEnd() throws Exception {
+ @Test
+ public void testSkip_AtEnd() throws Exception {
for (int i = 0; i < DATA_BYTES.length; i++) {
in.read();
}
@@ -133,11 +143,13 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
assertEquals(-1, in.read());
}
- @Test public void testAvailable() throws Exception {
+ @Test
+ public void testAvailable() throws Exception {
for (int i = DATA_BYTES.length; i > 0; i--) {
assertEquals(i, in.available());
in.read();
}
assertEquals(0, in.available());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
index da4ebaffc..bc8840729 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,7 +19,7 @@
package org.apache.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -31,7 +31,6 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.InputArchive;
import org.apache.zookeeper.CreateMode;
@@ -43,16 +42,15 @@ import org.apache.zookeeper.server.persistence.FileSnap;
import org.apache.zookeeper.server.persistence.FileTxnLog;
import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class CRCTest extends ZKTestCase{
+public class CRCTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(CRCTest.class);
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
/**
* corrupt a file by writing m at 500 b
* offset
@@ -61,7 +59,7 @@ public class CRCTest extends ZKTestCase{
*/
private void corruptFile(File file) throws IOException {
// corrupt the logfile
- RandomAccessFile raf = new RandomAccessFile(file, "rw");
+ RandomAccessFile raf = new RandomAccessFile(file, "rw");
byte[] b = "mahadev".getBytes();
long writeLen = 500L;
raf.seek(writeLen);
@@ -74,8 +72,7 @@ public class CRCTest extends ZKTestCase{
private boolean getCheckSum(FileSnap snap, File snapFile) throws IOException {
DataTree dt = new DataTree();
Map<Long, Integer> sessions = new ConcurrentHashMap<Long, Integer>();
- InputStream snapIS = new BufferedInputStream(new FileInputStream(
- snapFile));
+ InputStream snapIS = new BufferedInputStream(new FileInputStream(snapFile));
CheckedInputStream crcIn = new CheckedInputStream(snapIS, new Adler32());
InputArchive ia = BinaryInputArchive.getArchive(crcIn);
try {
@@ -113,22 +110,18 @@ public class CRCTest extends ZKTestCase{
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
- for (int i =0; i < 2000; i++) {
- zk.create("/crctest- " + i , ("/crctest- " + i).getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ for (int i = 0; i < 2000; i++) {
+ zk.create("/crctest- " + i, ("/crctest- " + i).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
File versionDir = new File(tmpDir, "version-2");
File[] list = versionDir.listFiles();
@@ -136,7 +129,7 @@ public class CRCTest extends ZKTestCase{
// one the snapshot and the other logFile
File snapFile = null;
File logFile = null;
- for (File file: list) {
+ for (File file : list) {
LOG.info("file is " + file);
if (file.getName().startsWith("log")) {
logFile = file;
@@ -149,8 +142,8 @@ public class CRCTest extends ZKTestCase{
try {
while (itr.next()) {
}
- Assert.assertTrue(false);
- } catch(IOException ie) {
+ assertTrue(false);
+ } catch (IOException ie) {
LOG.info("crc corruption", ie);
}
itr.close();
@@ -162,7 +155,7 @@ public class CRCTest extends ZKTestCase{
boolean cfile = false;
try {
cfile = getCheckSum(snap, snapFile);
- } catch(IOException ie) {
+ } catch (IOException ie) {
//the last snapshot seems incompelte
// corrupt the last but one
// and use that
@@ -170,6 +163,7 @@ public class CRCTest extends ZKTestCase{
corruptFile(snapFile);
cfile = getCheckSum(snap, snapFile);
}
- Assert.assertTrue(cfile);
- }
+ assertTrue(cfile);
+ }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
index 47d406f3c..2b10f9be1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,19 +18,13 @@
package org.apache.zookeeper.server;
+import static org.apache.zookeeper.server.NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Assert;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
@@ -41,25 +35,30 @@ import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-
-import static org.apache.zookeeper.server.NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.test.ClientBase;
+import org.apache.zookeeper.test.QuorumUtil;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ConnectionMetricsTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ConnectionMetricsTest.class);
@Test
- public void testRevalidateCount() throws Exception {
+ public void testRevalidateCount() throws Exception {
ServerMetrics.getMetrics().resetAll();
QuorumUtil util = new QuorumUtil(1); // create a quorum of 3 servers
// disable local session to make sure we create a global session
util.enableLocalSession(false);
util.startAll();
- int follower1 = (int)util.getFollowerQuorumPeers().get(0).getId();
- int follower2 = (int)util.getFollowerQuorumPeers().get(1).getId();
+ int follower1 = (int) util.getFollowerQuorumPeers().get(0).getId();
+ int follower2 = (int) util.getFollowerQuorumPeers().get(1).getId();
LOG.info("connecting to server: {}", follower1);
ClientBase.CountdownWatcher watcher = new ClientBase.CountdownWatcher();
// create a connection to follower
@@ -79,18 +78,16 @@ public class ConnectionMetricsTest extends ZKTestCase {
LOG.info("reconnected");
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("connection_revalidate_count"));
- Assert.assertEquals(1L, values.get("revalidate_count"));
+ assertEquals(1L, values.get("connection_revalidate_count"));
+ assertEquals(1L, values.get("revalidate_count"));
zk.close();
util.shutdownAll();
}
+ private class MockNIOServerCnxn extends NIOServerCnxn {
- private class MockNIOServerCnxn extends NIOServerCnxn {
- public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock,
- SelectionKey sk, NIOServerCnxnFactory factory,
- NIOServerCnxnFactory.SelectorThread selectorThread) throws IOException {
+ public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock, SelectionKey sk, NIOServerCnxnFactory factory, NIOServerCnxnFactory.SelectorThread selectorThread) throws IOException {
super(zk, sock, sk, factory, selectorThread);
}
@@ -98,6 +95,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
protected boolean isSocketOpen() {
return true;
}
+
}
private static class FakeSK extends SelectionKey {
@@ -160,7 +158,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
cnxn.doIO(new FakeSK());
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("connection_drop_count"));
+ assertEquals(1L, values.get("connection_drop_count"));
}
@Test
@@ -182,7 +180,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
cnxn.close();
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("connection_drop_count"));
+ assertEquals(1L, values.get("connection_drop_count"));
}
@Test
@@ -190,8 +188,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
ServerCnxnFactory factory = new NIOServerCnxnFactory();
factory.configure(new InetSocketAddress(PortAssignment.unique()), 1000);
factory.start();
- int timeout = Integer.getInteger(
- ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT, 10000);
+ int timeout = Integer.getInteger(ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT, 10000);
ServerMetrics.getMetrics().resetAll();
// add two connections w/o touching them so they will expire
@@ -200,13 +197,13 @@ public class ConnectionMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
int sleptTime = 0;
- while (values.get("sessionless_connections_expired") == null || sleptTime < 2*timeout){
+ while (values.get("sessionless_connections_expired") == null || sleptTime < 2 * timeout) {
Thread.sleep(100);
sleptTime += 100;
values = MetricsUtils.currentServerMetrics();
}
- Assert.assertEquals(2L, values.get("sessionless_connections_expired"));
+ assertEquals(2L, values.get("sessionless_connections_expired"));
factory.shutdown();
}
@@ -214,8 +211,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
@Test
public void testStaleSessionsExpired() throws Exception {
int tickTime = 1000;
- SessionTrackerImpl tracker = new SessionTrackerImpl(mock(ZooKeeperServer.class),
- new ConcurrentHashMap<>(), tickTime, 1L, null);
+ SessionTrackerImpl tracker = new SessionTrackerImpl(mock(ZooKeeperServer.class), new ConcurrentHashMap<>(), tickTime, 1L, null);
tracker.sessionsById.put(1L, mock(SessionTrackerImpl.SessionImpl.class));
tracker.sessionsById.put(2L, mock(SessionTrackerImpl.SessionImpl.class));
@@ -229,14 +225,15 @@ public class ConnectionMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
int sleptTime = 0;
- while (values.get("stale_sessions_expired") == null || sleptTime < 2*tickTime) {
+ while (values.get("stale_sessions_expired") == null || sleptTime < 2 * tickTime) {
Thread.sleep(100);
sleptTime += 100;
values = MetricsUtils.currentServerMetrics();
}
- Assert.assertEquals(2L, values.get("stale_sessions_expired"));
+ assertEquals(2L, values.get("stale_sessions_expired"));
tracker.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
index 4889684f7..83c7f0b3d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,18 +18,32 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.*;
-import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
-import java.util.concurrent.*;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.AsyncCallback;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.Op;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.Test;
public class CreateContainerTest extends ClientBase {
+
private ZooKeeper zk;
@Override
@@ -45,89 +59,76 @@ public class CreateContainerTest extends ClientBase {
}
@Test(timeout = 30000)
- public void testCreate()
- throws KeeperException, InterruptedException {
+ public void testCreate() throws KeeperException, InterruptedException {
createNoStatVerifyResult("/foo");
createNoStatVerifyResult("/foo/child");
}
@Test(timeout = 30000)
- public void testCreateWithStat()
- throws KeeperException, InterruptedException {
+ public void testCreateWithStat() throws KeeperException, InterruptedException {
Stat stat = createWithStatVerifyResult("/foo");
Stat childStat = createWithStatVerifyResult("/foo/child");
// Don't expect to get the same stats for different creates.
- Assert.assertFalse(stat.equals(childStat));
+ assertFalse(stat.equals(childStat));
}
@SuppressWarnings("ConstantConditions")
@Test(timeout = 30000)
- public void testCreateWithNullStat()
- throws KeeperException, InterruptedException {
+ public void testCreateWithNullStat() throws KeeperException, InterruptedException {
final String name = "/foo";
- Assert.assertNull(zk.exists(name, false));
+ assertNull(zk.exists(name, false));
Stat stat = null;
// If a null Stat object is passed the create should still
// succeed, but no Stat info will be returned.
zk.create(name, name.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, stat);
- Assert.assertNull(stat);
- Assert.assertNotNull(zk.exists(name, false));
+ assertNull(stat);
+ assertNotNull(zk.exists(name, false));
}
@Test(timeout = 30000)
- public void testSimpleDeletion()
- throws KeeperException, InterruptedException {
+ public void testSimpleDeletion() throws KeeperException, InterruptedException {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo/bar", -1); // should cause "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testMultiWithContainerSimple()
- throws KeeperException, InterruptedException {
- Op createContainer = Op.create("/foo", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
+ public void testMultiWithContainerSimple() throws KeeperException, InterruptedException {
+ Op createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.multi(Collections.singletonList(createContainer));
DataTree dataTree = serverFactory.getZooKeeperServer().getZKDatabase().getDataTree();
- Assert.assertEquals(dataTree.getContainers().size(), 1);
+ assertEquals(dataTree.getContainers().size(), 1);
}
@Test(timeout = 30000)
- public void testMultiWithContainer()
- throws KeeperException, InterruptedException {
- Op createContainer = Op.create("/foo", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
- Op createChild = Op.create("/foo/bar", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ public void testMultiWithContainer() throws KeeperException, InterruptedException {
+ Op createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
+ Op createChild = Op.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.multi(Arrays.asList(createContainer, createChild));
DataTree dataTree = serverFactory.getZooKeeperServer().getZKDatabase().getDataTree();
- Assert.assertEquals(dataTree.getContainers().size(), 1);
+ assertEquals(dataTree.getContainers().size(), 1);
zk.delete("/foo/bar", -1); // should cause "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
- createContainer = Op.create("/foo", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
- createChild = Op.create("/foo/bar", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
+ createChild = Op.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Op deleteChild = Op.delete("/foo/bar", -1);
zk.multi(Arrays.asList(createContainer, createChild, deleteChild));
@@ -135,62 +136,55 @@ public class CreateContainerTest extends ClientBase {
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testSimpleDeletionAsync()
- throws KeeperException, InterruptedException {
+ public void testSimpleDeletionAsync() throws KeeperException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
AsyncCallback.Create2Callback cb = new AsyncCallback.Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
- Assert.assertEquals(ctx, "context");
+ assertEquals(ctx, "context");
latch.countDown();
}
};
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, cb, "context");
- Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
+ assertTrue(latch.await(5, TimeUnit.SECONDS));
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo/bar", -1); // should cause "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testCascadingDeletion()
- throws KeeperException, InterruptedException {
+ public void testCascadingDeletion() throws KeeperException, InterruptedException {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar/one", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo/bar/one", -1); // should cause "/foo/bar" and "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- containerManager
- .checkContainers();
+ containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo/bar", false));
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo/bar", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testFalseEmpty()
- throws KeeperException, InterruptedException {
+ public void testFalseEmpty() throws KeeperException, InterruptedException {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
@Override
protected Collection<String> getCandidates() {
return Collections.singletonList("/foo");
@@ -199,12 +193,11 @@ public class CreateContainerTest extends ClientBase {
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNotNull("Container should have not been deleted", zk.exists("/foo", false));
+ assertNotNull("Container should have not been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testMaxPerMinute()
- throws InterruptedException {
+ public void testMaxPerMinute() throws InterruptedException {
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
RequestProcessor processor = new RequestProcessor() {
@Override
@@ -216,8 +209,7 @@ public class CreateContainerTest extends ClientBase {
public void shutdown() {
}
};
- final ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), processor, 1, 2) {
+ final ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), processor, 1, 2) {
@Override
protected long getMinIntervalMs() {
return 1000;
@@ -235,47 +227,45 @@ public class CreateContainerTest extends ClientBase {
return null;
}
});
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/one");
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/two");
- Assert.assertEquals(queue.size(), 0);
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/one");
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/two");
+ assertEquals(queue.size(), 0);
Thread.sleep(500);
- Assert.assertEquals(queue.size(), 0);
+ assertEquals(queue.size(), 0);
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/three");
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/four");
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/three");
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/four");
}
- private void createNoStatVerifyResult(String newName)
- throws KeeperException, InterruptedException {
- Assert.assertNull("Node existed before created", zk.exists(newName, false));
+ private void createNoStatVerifyResult(String newName) throws KeeperException, InterruptedException {
+ assertNull("Node existed before created", zk.exists(newName, false));
zk.create(newName, newName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
- Assert.assertNotNull("Node was not created as expected",
- zk.exists(newName, false));
+ assertNotNull("Node was not created as expected", zk.exists(newName, false));
}
- private Stat createWithStatVerifyResult(String newName)
- throws KeeperException, InterruptedException {
- Assert.assertNull("Node existed before created", zk.exists(newName, false));
+ private Stat createWithStatVerifyResult(String newName) throws KeeperException, InterruptedException {
+ assertNull("Node existed before created", zk.exists(newName, false));
Stat stat = new Stat();
zk.create(newName, newName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, stat);
validateCreateStat(stat, newName);
Stat referenceStat = zk.exists(newName, false);
- Assert.assertNotNull("Node was not created as expected", referenceStat);
- Assert.assertEquals(referenceStat, stat);
+ assertNotNull("Node was not created as expected", referenceStat);
+ assertEquals(referenceStat, stat);
return stat;
}
private void validateCreateStat(Stat stat, String name) {
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
index 2440030cc..b4c8fa02b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,15 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -32,23 +41,19 @@ import org.apache.zookeeper.proto.CreateTTLRequest;
import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-
public class CreateTTLTest extends ClientBase {
+
private TestableZooKeeper zk;
private static final Collection<String> disabledTests = Collections.singleton("testDisabled");
@Override
public void setUp() throws Exception {
- System.setProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY, disabledTests.contains(getTestName()) ? "false" : "true");
+ System.setProperty(
+ EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY,
+ disabledTests.contains(getTestName()) ? "false" : "true");
super.setUpWithServerId(254);
zk = createClient();
}
@@ -61,20 +66,19 @@ public class CreateTTLTest extends ClientBase {
}
@Test
- public void testCreate()
- throws KeeperException, InterruptedException {
+ public void testCreate() throws KeeperException, InterruptedException {
Stat stat = new Stat();
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
@@ -82,23 +86,19 @@ public class CreateTTLTest extends ClientBase {
RequestHeader h = new RequestHeader(1, ZooDefs.OpCode.createTTL);
String path = "/bad_ttl";
- CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_WITH_TTL.toFlag(), -100);
+ CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(), -100);
CreateResponse response = new CreateResponse();
ReplyHeader r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals("An invalid CreateTTLRequest should throw BadArguments",
- r.getErr(), Code.BADARGUMENTS.intValue());
- Assert.assertNull("An invalid CreateTTLRequest should not result in znode creation",
- zk.exists(path, false));
+ assertEquals("An invalid CreateTTLRequest should throw BadArguments", r.getErr(), Code.BADARGUMENTS.intValue());
+ assertNull("An invalid CreateTTLRequest should not result in znode creation", zk.exists(path, false));
- request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue() + 1);
+ request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(),
+ EphemeralType.TTL.maxValue()
+ + 1);
response = new CreateResponse();
r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals("An invalid CreateTTLRequest should throw BadArguments",
- r.getErr(), Code.BADARGUMENTS.intValue());
- Assert.assertNull("An invalid CreateTTLRequest should not result in znode creation",
- zk.exists(path, false));
+ assertEquals("An invalid CreateTTLRequest should throw BadArguments", r.getErr(), Code.BADARGUMENTS.intValue());
+ assertNull("An invalid CreateTTLRequest should not result in znode creation", zk.exists(path, false));
}
@Test
@@ -106,36 +106,31 @@ public class CreateTTLTest extends ClientBase {
RequestHeader h = new RequestHeader(1, ZooDefs.OpCode.createTTL);
String path = "/bad_ttl";
- CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue());
+ CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue());
CreateResponse response = new CreateResponse();
ReplyHeader r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals("EphemeralType.getMaxTTL() should succeed",
- r.getErr(), Code.OK.intValue());
- Assert.assertNotNull("Node should exist",
- zk.exists(path, false));
+ assertEquals("EphemeralType.getMaxTTL() should succeed", r.getErr(), Code.OK.intValue());
+ assertNotNull("Node should exist", zk.exists(path, false));
}
@Test
- public void testCreateSequential()
- throws KeeperException, InterruptedException {
+ public void testCreateSequential() throws KeeperException, InterruptedException {
Stat stat = new Stat();
String path = zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists(path, false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists(path, false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists(path, false));
+ assertNull("Ttl node should have been deleted", zk.exists(path, false));
}
@Test
- public void testCreateAsync()
- throws KeeperException, InterruptedException {
+ public void testCreateAsync() throws KeeperException, InterruptedException {
AsyncCallback.Create2Callback callback = new AsyncCallback.Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
@@ -147,78 +142,76 @@ public class CreateTTLTest extends ClientBase {
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
- public void testModifying()
- throws KeeperException, InterruptedException {
+ public void testModifying() throws KeeperException, InterruptedException {
Stat stat = new Stat();
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
- for ( int i = 0; i < 10; ++i ) {
+ for (int i = 0; i < 10; ++i) {
fakeElapsed.set(50);
zk.setData("/foo", new byte[i + 1], -1);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
}
fakeElapsed.set(200);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
- public void testMulti()
- throws KeeperException, InterruptedException {
+ public void testMulti() throws KeeperException, InterruptedException {
Op createTtl = Op.create("/a", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, 100);
Op createTtlSequential = Op.create("/b", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL, 200);
Op createNonTtl = Op.create("/c", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
List<OpResult> results = zk.multi(Arrays.asList(createTtl, createTtlSequential, createNonTtl));
- String sequentialPath = ((OpResult.CreateResult)results.get(1)).getPath();
+ String sequentialPath = ((OpResult.CreateResult) results.get(1)).getPath();
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("node should not have been deleted yet", zk.exists("/a", false));
- Assert.assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
- Assert.assertNotNull("node should never be deleted", zk.exists("/c", false));
+ assertNotNull("node should not have been deleted yet", zk.exists("/a", false));
+ assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
+ assertNotNull("node should never be deleted", zk.exists("/c", false));
fakeElapsed.set(110);
containerManager.checkContainers();
- Assert.assertNull("node should have been deleted", zk.exists("/a", false));
- Assert.assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
- Assert.assertNotNull("node should never be deleted", zk.exists("/c", false));
+ assertNull("node should have been deleted", zk.exists("/a", false));
+ assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
+ assertNotNull("node should never be deleted", zk.exists("/c", false));
fakeElapsed.set(210);
containerManager.checkContainers();
- Assert.assertNull("node should have been deleted", zk.exists("/a", false));
- Assert.assertNull("node should have been deleted", zk.exists(sequentialPath, false));
- Assert.assertNotNull("node should never be deleted", zk.exists("/c", false));
+ assertNull("node should have been deleted", zk.exists("/a", false));
+ assertNull("node should have been deleted", zk.exists(sequentialPath, false));
+ assertNotNull("node should never be deleted", zk.exists("/c", false));
}
@Test
public void testBadUsage() throws KeeperException, InterruptedException {
- for ( CreateMode createMode : CreateMode.values() ) {
+ for (CreateMode createMode : CreateMode.values()) {
try {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode, new Stat(), createMode.isTTL() ? 0 : 100);
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
}
- for ( CreateMode createMode : CreateMode.values() ) {
+ for (CreateMode createMode : CreateMode.values()) {
AsyncCallback.Create2Callback callback = new AsyncCallback.Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
@@ -227,7 +220,7 @@ public class CreateTTLTest extends ClientBase {
};
try {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode, callback, null, createMode.isTTL() ? 0 : 100);
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
@@ -236,14 +229,14 @@ public class CreateTTLTest extends ClientBase {
try {
Op op = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, 0);
zk.multi(Collections.singleton(op));
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
try {
Op op = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL, 0);
zk.multi(Collections.singleton(op));
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
@@ -256,12 +249,12 @@ public class CreateTTLTest extends ClientBase {
}
private ContainerManager newContainerManager(final AtomicLong fakeElapsed) {
- return new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
+ return new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
@Override
protected long getElapsed(DataNode node) {
return fakeElapsed.get();
}
};
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
index 628976604..0fb6f6864 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,12 +15,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.server;
-import static org.junit.Assert.*;
+package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
import java.util.Set;
-
import org.junit.Test;
public class DataNodeTest {
@@ -62,4 +63,5 @@ public class DataNodeTest {
// do nothing
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
index 5c8fb4183..9ca568647 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,58 +18,57 @@
package org.apache.zookeeper.server;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.jute.BinaryInputArchive;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
+import org.apache.zookeeper.Quotas;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.data.ACL;
+import org.apache.zookeeper.common.PathTrie;
import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.util.DigestCalculator;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import org.apache.zookeeper.Quotas;
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.common.PathTrie;
-import java.lang.reflect.*;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.List;
-import java.util.ArrayList;
-import org.apache.zookeeper.metrics.MetricsUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DataTreeTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(DataTreeTest.class);
private DataTree dt;
@Before
public void setUp() throws Exception {
- dt=new DataTree();
+ dt = new DataTree();
}
@After
public void tearDown() throws Exception {
- dt=null;
+ dt = null;
}
/**
@@ -84,8 +83,7 @@ public class DataTreeTest extends ZKTestCase {
final DataTree dataTree = new DataTree();
LOG.info("Create {} zkclient sessions and its ephemeral nodes", count);
createEphemeralNode(session, dataTree, count);
- final AtomicBoolean exceptionDuringDumpEphemerals = new AtomicBoolean(
- false);
+ final AtomicBoolean exceptionDuringDumpEphemerals = new AtomicBoolean(false);
final AtomicBoolean running = new AtomicBoolean(true);
Thread thread = new Thread() {
public void run() {
@@ -98,47 +96,47 @@ public class DataTreeTest extends ZKTestCase {
LOG.error("Received exception while dumpEphemerals!", e);
exceptionDuringDumpEphemerals.set(true);
}
- };
+ }
};
thread.start();
LOG.debug("Killing {} zkclient sessions and its ephemeral nodes", count);
killZkClientSession(session, zxid, dataTree, count);
running.set(false);
thread.join();
- Assert.assertFalse("Should have got exception while dumpEphemerals!",
- exceptionDuringDumpEphemerals.get());
+ assertFalse("Should have got exception while dumpEphemerals!", exceptionDuringDumpEphemerals.get());
}
- private void killZkClientSession(long session, long zxid,
- final DataTree dataTree, int count) {
+ private void killZkClientSession(long session, long zxid, final DataTree dataTree, int count) {
for (int i = 0; i < count; i++) {
dataTree.killSession(session + i, zxid);
}
}
- private void createEphemeralNode(long session, final DataTree dataTree,
- int count) throws NoNodeException, NodeExistsException {
+ private void createEphemeralNode(long session, final DataTree dataTree, int count) throws NoNodeException, NodeExistsException {
for (int i = 0; i < count; i++) {
- dataTree.createNode("/test" + i, new byte[0], null, session + i,
- dataTree.getNode("/").stat.getCversion() + 1, 1, 1);
+ dataTree.createNode("/test" + i, new byte[0], null, session + i, dataTree.getNode("/").stat.getCversion()
+ + 1, 1, 1);
}
}
@Test(timeout = 60000)
public void testRootWatchTriggered() throws Exception {
- class MyWatcher implements Watcher{
- boolean fired=false;
+ class MyWatcher implements Watcher {
+
+ boolean fired = false;
public void process(WatchedEvent event) {
- if(event.getPath().equals("/"))
- fired=true;
+ if (event.getPath().equals("/")) {
+ fired = true;
+ }
}
+
}
- MyWatcher watcher=new MyWatcher();
+ MyWatcher watcher = new MyWatcher();
// set a watch on the root node
dt.getChildren("/", new Stat(), watcher);
// add a new node, should trigger a watch
- dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
- Assert.assertFalse("Root node watch not triggered",!watcher.fired);
+ dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1);
+ assertFalse("Root node watch not triggered", !watcher.fired);
}
/**
@@ -149,19 +147,24 @@ public class DataTreeTest extends ZKTestCase {
try {
DigestCalculator.setDigestEnabled(true);
DataTree dt = new DataTree();
- dt.createNode("/test", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
+ dt.createNode("/test", new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1);
DataNode zk = dt.getNode("/test");
int prevCversion = zk.stat.getCversion();
long prevPzxid = zk.stat.getPzxid();
long digestBefore = dt.getTreeDigest();
- dt.setCversionPzxid("/test/", prevCversion + 1, prevPzxid + 1);
+ dt.setCversionPzxid("/test/", prevCversion + 1, prevPzxid + 1);
int newCversion = zk.stat.getCversion();
long newPzxid = zk.stat.getPzxid();
- Assert.assertTrue("<cversion, pzxid> verification failed. Expected: <" +
- (prevCversion + 1) + ", " + (prevPzxid + 1) + ">, found: <" +
- newCversion + ", " + newPzxid + ">",
- (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
- Assert.assertNotEquals(digestBefore, dt.getTreeDigest());
+ assertTrue("<cversion, pzxid> verification failed. Expected: <"
+ + (prevCversion + 1)
+ + ", "
+ + (prevPzxid + 1)
+ + ">, found: <"
+ + newCversion
+ + ", "
+ + newPzxid
+ + ">", (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
+ assertNotEquals(digestBefore, dt.getTreeDigest());
} finally {
DigestCalculator.setDigestEnabled(false);
}
@@ -177,10 +180,15 @@ public class DataTreeTest extends ZKTestCase {
parent = dt.getNode("/");
int newCversion = parent.stat.getCversion();
long newPzxid = parent.stat.getPzxid();
- Assert.assertTrue("<cversion, pzxid> verification failed. Expected: <" +
- currentCversion + ", " + currentPzxid + ">, found: <" +
- newCversion + ", " + newPzxid + ">",
- (newCversion >= currentCversion && newPzxid >= currentPzxid));
+ assertTrue("<cversion, pzxid> verification failed. Expected: <"
+ + currentCversion
+ + ", "
+ + currentPzxid
+ + ">, found: <"
+ + newCversion
+ + ", "
+ + newPzxid
+ + ">", (newCversion >= currentCversion && newPzxid >= currentPzxid));
}
@Test
@@ -195,7 +203,7 @@ public class DataTreeTest extends ZKTestCase {
} catch (NoNodeException e) { /* expected */ }
root = dt.getNode("/");
currentPzxid = root.stat.getPzxid();
- Assert.assertEquals(currentPzxid, zxid);
+ assertEquals(currentPzxid, zxid);
// pzxid not updated with smaller zxid
long prevPzxid = currentPzxid;
@@ -205,24 +213,22 @@ public class DataTreeTest extends ZKTestCase {
} catch (NoNodeException e) { /* expected */ }
root = dt.getNode("/");
currentPzxid = root.stat.getPzxid();
- Assert.assertEquals(currentPzxid, prevPzxid);
+ assertEquals(currentPzxid, prevPzxid);
}
@Test
public void testDigestUpdatedWhenReplayCreateTxnForExistNode() {
try {
DigestCalculator.setDigestEnabled(true);
- dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create),
- new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
+ dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create), new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
// create the same node with a higher cversion to simulate the
// scenario when replaying a create txn for an existing node due
// to fuzzy snapshot
- dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create),
- new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 2));
+ dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create), new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 2));
// check the current digest value
- Assert.assertEquals(dt.getTreeDigest(), dt.getLastProcessedZxidDigest().digest);
+ assertEquals(dt.getTreeDigest(), dt.getLastProcessedZxidDigest().digest);
} finally {
DigestCalculator.setDigestEnabled(false);
}
@@ -235,7 +241,7 @@ public class DataTreeTest extends ZKTestCase {
DataTree dserTree = new DataTree();
dserTree.createNode("/bug", new byte[20], null, -1, 1, 1, 1);
- dserTree.createNode(Quotas.quotaZookeeper+"/bug", null, null, -1, 1, 1, 1);
+ dserTree.createNode(Quotas.quotaZookeeper + "/bug", null, null, -1, 1, 1, 1);
dserTree.createNode(Quotas.quotaPath("/bug"), new byte[20], null, -1, 1, 1, 1);
dserTree.createNode(Quotas.statPath("/bug"), new byte[20], null, -1, 1, 1, 1);
@@ -253,10 +259,10 @@ public class DataTreeTest extends ZKTestCase {
Field pfield = DataTree.class.getDeclaredField("pTrie");
pfield.setAccessible(true);
- PathTrie pTrie = (PathTrie)pfield.get(dserTree);
+ PathTrie pTrie = (PathTrie) pfield.get(dserTree);
//Check that the node path is removed from pTrie
- Assert.assertEquals("/bug is still in pTrie", "/", pTrie.findMaxPrefix("/bug"));
+ assertEquals("/bug is still in pTrie", "/", pTrie.findMaxPrefix("/bug"));
}
/*
@@ -270,7 +276,7 @@ public class DataTreeTest extends ZKTestCase {
@Test(timeout = 60000)
public void testSerializeDoesntLockDataNodeWhileWriting() throws Exception {
DataTree tree = new DataTree();
- tree.createNode("/marker", new byte[] {42}, null, -1, 1, 1, 1);
+ tree.createNode("/marker", new byte[]{42}, null, -1, 1, 1, 1);
final DataNode markerNode = tree.getNode("/marker");
final AtomicBoolean ranTestCase = new AtomicBoolean();
DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
@@ -297,7 +303,7 @@ public class DataTreeTest extends ZKTestCase {
boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
//This is the real assertion - could another thread lock
//the DataNode we're currently writing
- Assert.assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
+ assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
@@ -312,7 +318,7 @@ public class DataTreeTest extends ZKTestCase {
tree.serialize(oa, "test");
//Let's make sure that we hit the code that ran the real assertion above
- Assert.assertTrue("Didn't find the expected node", ranTestCase.get());
+ assertTrue("Didn't find the expected node", ranTestCase.get());
}
@Test(timeout = 60000)
@@ -324,12 +330,10 @@ public class DataTreeTest extends ZKTestCase {
tree.deleteNode(ZooDefs.CONFIG_NODE, 1);
tree.getReferenceCountedAclCache().aclIndex = 0;
- Assert.assertEquals(
- "expected to have 1 acl in acl cache map", 0, tree.aclCacheSize());
+ assertEquals("expected to have 1 acl in acl cache map", 0, tree.aclCacheSize());
// serialize the data with one znode with acl
- tree.createNode(
- "/bug", new byte[20], ZooDefs.Ids.OPEN_ACL_UNSAFE, -1, 1, 1, 1);
+ tree.createNode("/bug", new byte[20], ZooDefs.Ids.OPEN_ACL_UNSAFE, -1, 1, 1, 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
@@ -340,41 +344,35 @@ public class DataTreeTest extends ZKTestCase {
BinaryInputArchive ia = BinaryInputArchive.getArchive(bais);
tree.deserialize(ia, "test");
- Assert.assertEquals(
- "expected to have 1 acl in acl cache map", 1, tree.aclCacheSize());
- Assert.assertEquals(
- "expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE,
- tree.getACL("/bug", new Stat()));
+ assertEquals("expected to have 1 acl in acl cache map", 1, tree.aclCacheSize());
+ assertEquals("expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()));
// simulate the upgrading case where the config node will be created
// again after leader election
tree.addConfigNode();
- Assert.assertEquals(
- "expected to have 2 acl in acl cache map", 2, tree.aclCacheSize());
- Assert.assertEquals(
- "expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE,
- tree.getACL("/bug", new Stat()));
+ assertEquals("expected to have 2 acl in acl cache map", 2, tree.aclCacheSize());
+ assertEquals("expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()));
}
@Test
public void testCachedApproximateDataSize() throws Exception {
DataTree dt = new DataTree();
long initialSize = dt.approximateDataSize();
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
// create a node
dt.createNode("/testApproximateDataSize", new byte[20], null, -1, 1, 1, 1);
dt.createNode("/testApproximateDataSize1", new byte[20], null, -1, 1, 1, 1);
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
// update data
dt.setData("/testApproximateDataSize1", new byte[32], -1, 1, 1);
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
// delete a node
dt.deleteNode("/testApproximateDataSize", -1);
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
}
@Test
@@ -386,18 +384,17 @@ public class DataTreeTest extends ZKTestCase {
dt.createNode("/all_children_test/nodes/node1", new byte[20], null, -1, 1, 1, 1);
dt.createNode("/all_children_test/nodes/node2", new byte[20], null, -1, 1, 1, 1);
dt.createNode("/all_children_test/nodes/node3", new byte[20], null, -1, 1, 1, 1);
- Assert.assertEquals(4, dt.getAllChildrenNumber("/all_children_test"));
- Assert.assertEquals(3, dt.getAllChildrenNumber("/all_children_test/nodes"));
- Assert.assertEquals(0, dt.getAllChildrenNumber("/all_children_test/nodes/node1"));
+ assertEquals(4, dt.getAllChildrenNumber("/all_children_test"));
+ assertEquals(3, dt.getAllChildrenNumber("/all_children_test/nodes"));
+ assertEquals(0, dt.getAllChildrenNumber("/all_children_test/nodes/node1"));
//add these three init nodes:/zookeeper,/zookeeper/quota,/zookeeper/config,so the number is 8.
- Assert.assertEquals( 8, dt.getAllChildrenNumber("/"));
+ assertEquals(8, dt.getAllChildrenNumber("/"));
}
@Test
public void testDataTreeMetrics() throws Exception {
ServerMetrics.getMetrics().resetAll();
-
long readBytes1 = 0;
long readBytes2 = 0;
long writeBytes1 = 0;
@@ -437,18 +434,18 @@ public class DataTreeTest extends ZKTestCase {
readBytes1 += TOP1PATH.length() + CHILD1.length() + CHILD2.length() + DataTree.STAT_OVERHEAD_BYTES;
dt.deleteNode(TOP1PATH, 1);
writeBytes1 += TOP1PATH.length();
-
+
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- System.out.println("values:"+values);
- Assert.assertEquals(writeBytes1, values.get("sum_" + TOP1+ "_write_per_namespace"));
- Assert.assertEquals(5L, values.get("cnt_" + TOP1 + "_write_per_namespace"));
- Assert.assertEquals(writeBytes2, values.get("sum_" + TOP2+ "_write_per_namespace"));
- Assert.assertEquals(1L, values.get("cnt_" + TOP2 + "_write_per_namespace"));
-
- Assert.assertEquals(readBytes1, values.get("sum_" + TOP1+ "_read_per_namespace"));
- Assert.assertEquals(3L, values.get("cnt_" + TOP1 + "_read_per_namespace"));
- Assert.assertEquals(readBytes2, values.get("sum_" + TOP2+ "_read_per_namespace"));
- Assert.assertEquals(1L, values.get("cnt_" + TOP2 + "_read_per_namespace"));
+ System.out.println("values:" + values);
+ assertEquals(writeBytes1, values.get("sum_" + TOP1 + "_write_per_namespace"));
+ assertEquals(5L, values.get("cnt_" + TOP1 + "_write_per_namespace"));
+ assertEquals(writeBytes2, values.get("sum_" + TOP2 + "_write_per_namespace"));
+ assertEquals(1L, values.get("cnt_" + TOP2 + "_write_per_namespace"));
+
+ assertEquals(readBytes1, values.get("sum_" + TOP1 + "_read_per_namespace"));
+ assertEquals(3L, values.get("cnt_" + TOP1 + "_read_per_namespace"));
+ assertEquals(readBytes2, values.get("sum_" + TOP2 + "_read_per_namespace"));
+ assertEquals(1L, values.get("cnt_" + TOP2 + "_read_per_namespace"));
}
/**
@@ -466,31 +463,32 @@ public class DataTreeTest extends ZKTestCase {
// create a node and check the digest is updated
long previousDigest = dt.getTreeDigest();
dt.createNode("/digesttest", new byte[0], null, -1, 1, 1, 1);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
// create a child and check the digest is updated
previousDigest = dt.getTreeDigest();
dt.createNode("/digesttest/1", "1".getBytes(), null, -1, 2, 2, 2);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
-
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
+
// check the digest is not chhanged when creating the same node
previousDigest = dt.getTreeDigest();
try {
dt.createNode("/digesttest/1", "1".getBytes(), null, -1, 2, 2, 2);
} catch (NodeExistsException e) { /* ignore */ }
- Assert.assertEquals(dt.getTreeDigest(), previousDigest);
+ assertEquals(dt.getTreeDigest(), previousDigest);
- // check digest with updated data
+ // check digest with updated data
previousDigest = dt.getTreeDigest();
dt.setData("/digesttest/1", "2".getBytes(), 3, 3, 3);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
// check digest with deleted node
previousDigest = dt.getTreeDigest();
dt.deleteNode("/digesttest/1", 5);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
} finally {
DigestCalculator.setDigestEnabled(false);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
index 9d93013e1..d8b21850e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -21,14 +21,11 @@ package org.apache.zookeeper.server;
import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.COMPLETED;
import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.NOT_STARTED;
import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.STARTED;
-
+import static org.junit.Assert.assertEquals;
import java.io.File;
-
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -49,38 +46,30 @@ public class DatadirCleanupManagerTest extends ZKTestCase {
public void testPurgeTask() throws Exception {
purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 1);
purgeMgr.start();
- Assert.assertEquals("Data log directory is not set as configured",
- dataLogDir, purgeMgr.getDataLogDir());
- Assert.assertEquals("Snapshot directory is not set as configured",
- snapDir, purgeMgr.getSnapDir());
- Assert.assertEquals("Snapshot retain count is not set as configured",
- 3, purgeMgr.getSnapRetainCount());
- Assert.assertEquals("Purge task is not started", STARTED, purgeMgr.getPurgeTaskStatus());
+ assertEquals("Data log directory is not set as configured", dataLogDir, purgeMgr.getDataLogDir());
+ assertEquals("Snapshot directory is not set as configured", snapDir, purgeMgr.getSnapDir());
+ assertEquals("Snapshot retain count is not set as configured", 3, purgeMgr.getSnapRetainCount());
+ assertEquals("Purge task is not started", STARTED, purgeMgr.getPurgeTaskStatus());
purgeMgr.shutdown();
- Assert.assertEquals("Purge task is still running after shutdown", COMPLETED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is still running after shutdown", COMPLETED, purgeMgr.getPurgeTaskStatus());
}
@Test
public void testWithZeroPurgeInterval() throws Exception {
purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 0);
purgeMgr.start();
- Assert.assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
purgeMgr.shutdown();
- Assert.assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
}
@Test
public void testWithNegativePurgeInterval() throws Exception {
purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, -1);
purgeMgr.start();
- Assert.assertEquals("Purge task is scheduled with negative purge interval",
- NOT_STARTED, purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
purgeMgr.shutdown();
- Assert.assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
}
@After
@@ -89,4 +78,5 @@ public class DatadirCleanupManagerTest extends ZKTestCase {
purgeMgr.shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
index b9f1df8cc..7b12b8452 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,24 +18,23 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DeserializationPerfTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(DeserializationPerfTest.class);
- private static void deserializeTree(int depth, int width, int len)
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ private static void deserializeTree(int depth, int width, int len) throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
BinaryInputArchive ia;
int count;
{
@@ -61,58 +60,59 @@ public class DeserializationPerfTest extends ZKTestCase {
long durationms = (end - start) / 1000000L;
long pernodeus = ((end - start) / 1000L) / count;
- Assert.assertEquals(count, dserTree.getNodeCount());
-
- LOG.info("Deserialized " + count + " nodes in " + durationms
- + " ms (" + pernodeus + "us/node), depth=" + depth + " width="
- + width + " datalen=" + len);
+ assertEquals(count, dserTree.getNodeCount());
+
+ LOG.info("Deserialized "
+ + count
+ + " nodes in "
+ + durationms
+ + " ms ("
+ + pernodeus
+ + "us/node), depth="
+ + depth
+ + " width="
+ + width
+ + " datalen="
+ + len);
}
@Test
- public void testSingleDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testSingleDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(1, 0, 20);
}
@Test
- public void testWideDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testWideDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(2, 10000, 20);
}
@Test
- public void testDeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testDeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(400, 1, 20);
}
@Test
- public void test10Wide5DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test10Wide5DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(5, 10, 20);
}
@Test
- public void test15Wide5DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test15Wide5DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(5, 15, 20);
}
@Test
- public void test25Wide4DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test25Wide4DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(4, 25, 20);
}
@Test
- public void test40Wide4DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test40Wide4DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(4, 40, 20);
}
@Test
- public void test300Wide3DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test300Wide3DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(3, 300, 20);
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
index 286fe4ed3..7967beb2c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,20 +18,22 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.concurrent.atomic.AtomicLong;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-
public class Emulate353TTLTest extends ClientBase {
+
private TestableZooKeeper zk;
@Override
@@ -51,57 +53,55 @@ public class Emulate353TTLTest extends ClientBase {
}
@Test
- public void testCreate()
- throws KeeperException, InterruptedException {
+ public void testCreate() throws KeeperException, InterruptedException {
Stat stat = new Stat();
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
- public void test353TTL()
- throws KeeperException, InterruptedException {
+ public void test353TTL() throws KeeperException, InterruptedException {
DataTree dataTree = serverFactory.zkServer.getZKDatabase().dataTree;
long ephemeralOwner = EphemeralTypeEmulate353.ttlToEphemeralOwner(100);
- dataTree.createNode("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, ephemeralOwner,
- dataTree.getNode("/").stat.getCversion()+1, 1, 1);
+ dataTree.createNode("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, ephemeralOwner, dataTree.getNode("/").stat.getCversion()
+ + 1, 1, 1);
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
public void testEphemeralOwner_emulationTTL() {
- Assert.assertThat(EphemeralType.get(-1), equalTo(EphemeralType.TTL));
+ assertThat(EphemeralType.get(-1), equalTo(EphemeralType.TTL));
}
@Test
public void testEphemeralOwner_emulationContainer() {
- Assert.assertThat(EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER), equalTo(EphemeralType.CONTAINER));
+ assertThat(EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER), equalTo(EphemeralType.CONTAINER));
}
private ContainerManager newContainerManager(final AtomicLong fakeElapsed) {
- return new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
+ return new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
@Override
protected long getElapsed(DataNode node) {
return fakeElapsed.get();
}
};
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
index 15904d0a9..5021f0f7c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,15 +18,17 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import static org.hamcrest.CoreMatchers.equalTo;
-
public class EphemeralTypeTest {
+
@Before
public void setUp() {
System.setProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY, "true");
@@ -39,11 +41,11 @@ public class EphemeralTypeTest {
@Test
public void testTtls() {
- long ttls[] = {100, 1, EphemeralType.TTL.maxValue()};
+ long[] ttls = {100, 1, EphemeralType.TTL.maxValue()};
for (long ttl : ttls) {
long ephemeralOwner = EphemeralType.TTL.toEphemeralOwner(ttl);
- Assert.assertEquals(EphemeralType.TTL, EphemeralType.get(ephemeralOwner));
- Assert.assertEquals(ttl, EphemeralType.TTL.getValue(ephemeralOwner));
+ assertEquals(EphemeralType.TTL, EphemeralType.get(ephemeralOwner));
+ assertEquals(ttl, EphemeralType.TTL.getValue(ephemeralOwner));
}
EphemeralType.validateTTL(CreateMode.PERSISTENT_WITH_TTL, 100);
@@ -51,7 +53,7 @@ public class EphemeralTypeTest {
try {
EphemeralType.validateTTL(CreateMode.EPHEMERAL, 100);
- Assert.fail("Should have thrown IllegalArgumentException");
+ fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// expected
}
@@ -59,25 +61,25 @@ public class EphemeralTypeTest {
@Test
public void testContainerValue() {
- Assert.assertEquals(Long.MIN_VALUE, EphemeralType.CONTAINER_EPHEMERAL_OWNER);
- Assert.assertEquals(EphemeralType.CONTAINER, EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER));
+ assertEquals(Long.MIN_VALUE, EphemeralType.CONTAINER_EPHEMERAL_OWNER);
+ assertEquals(EphemeralType.CONTAINER, EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER));
}
@Test
public void testNonSpecial() {
- Assert.assertEquals(EphemeralType.VOID, EphemeralType.get(0));
- Assert.assertEquals(EphemeralType.NORMAL, EphemeralType.get(1));
- Assert.assertEquals(EphemeralType.NORMAL, EphemeralType.get(Long.MAX_VALUE));
+ assertEquals(EphemeralType.VOID, EphemeralType.get(0));
+ assertEquals(EphemeralType.NORMAL, EphemeralType.get(1));
+ assertEquals(EphemeralType.NORMAL, EphemeralType.get(Long.MAX_VALUE));
}
@Test
public void testServerIds() {
- for ( int i = 0; i <= EphemeralType.MAX_EXTENDED_SERVER_ID; ++i ) {
+ for (int i = 0; i <= EphemeralType.MAX_EXTENDED_SERVER_ID; ++i) {
EphemeralType.validateServerId(i);
}
try {
EphemeralType.validateServerId(EphemeralType.MAX_EXTENDED_SERVER_ID + 1);
- Assert.fail("Should have thrown RuntimeException");
+ fail("Should have thrown RuntimeException");
} catch (RuntimeException e) {
// expected
}
@@ -87,7 +89,7 @@ public class EphemeralTypeTest {
public void testEphemeralOwner_extendedFeature_TTL() {
// 0xff = Extended feature is ON
// 0x0000 = Extended type id TTL (0)
- Assert.assertThat(EphemeralType.get(0xff00000000000000L), equalTo(EphemeralType.TTL));
+ assertThat(EphemeralType.get(0xff00000000000000L), equalTo(EphemeralType.TTL));
}
@Test(expected = IllegalArgumentException.class)
@@ -96,4 +98,5 @@ public class EphemeralTypeTest {
// 0x0001 = Unsupported extended type id (1)
EphemeralType.get(0xff00010000000000L);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
index dc56f831b..1d4309f04 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,21 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException;
@@ -33,24 +48,8 @@ import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class FinalRequestProcessorTest {
+
private List<ACL> testACLs = new ArrayList<ACL>();
private final Record[] responseRecord = new Record[1];
private final ReplyHeader[] replyHeaders = new ReplyHeader[1];
@@ -62,11 +61,7 @@ public class FinalRequestProcessorTest {
@Before
public void setUp() throws KeeperException.NoNodeException, IOException {
testACLs.clear();
- testACLs.addAll(Arrays.asList(
- new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:secrethash")),
- new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret")),
- new ACL(ZooDefs.Perms.READ, new Id("world", "anyone"))
- ));
+ testACLs.addAll(Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:secrethash")), new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret")), new ACL(ZooDefs.Perms.READ, new Id("world", "anyone"))));
ZooKeeperServer zks = new ZooKeeperServer();
ZKDatabase db = mock(ZKDatabase.class);
@@ -167,10 +162,7 @@ public class FinalRequestProcessorTest {
public void testACLDigestHashHiding_OnlyAdmin() {
// Arrange
testACLs.clear();
- testACLs.addAll(Arrays.asList(
- new ACL(ZooDefs.Perms.READ, new Id("digest", "user:secrethash")),
- new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret"))
- ));
+ testACLs.addAll(Arrays.asList(new ACL(ZooDefs.Perms.READ, new Id("digest", "user:secrethash")), new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret"))));
List<Id> authInfo = new ArrayList<Id>();
authInfo.add(new Id("digest", "adminuser:adminsecret"));
@@ -180,7 +172,7 @@ public class FinalRequestProcessorTest {
// Assert
assertTrue("Not a GetACL response. Auth failed?", responseRecord[0] instanceof GetACLResponse);
- GetACLResponse rsp = (GetACLResponse)responseRecord[0];
+ GetACLResponse rsp = (GetACLResponse) responseRecord[0];
assertThat("Number of ACLs in the response are different", rsp.getAcl().size(), equalTo(2));
// Verify ACLs in the response
@@ -190,7 +182,7 @@ public class FinalRequestProcessorTest {
private void assertMasked(boolean masked) {
assertTrue("Not a GetACL response. Auth failed?", responseRecord[0] instanceof GetACLResponse);
- GetACLResponse rsp = (GetACLResponse)responseRecord[0];
+ GetACLResponse rsp = (GetACLResponse) responseRecord[0];
assertThat("Number of ACLs in the response are different", rsp.getAcl().size(), equalTo(3));
// Verify ACLs in the response
@@ -227,4 +219,5 @@ public class FinalRequestProcessorTest {
assertThat("Original ACL list has been modified", testACLs.get(2).getId().getScheme(), equalTo("world"));
assertThat("Original ACL list has been modified", testACLs.get(2).getId().getId(), equalTo("anyone"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
index cd5af81d1..a7a4aeabe 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,31 +19,30 @@
package org.apache.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.PathUtils;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Test stand-alone server.
*
*/
public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
- protected static final Logger LOG =
- LoggerFactory.getLogger(InvalidSnapCountTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(InvalidSnapCountTest.class);
public static class MainThread extends Thread {
+
final File confFile;
final TestMain main;
@@ -62,11 +61,11 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
if (!dataDir.mkdir()) {
throw new IOException("unable to mkdir " + dataDir);
}
-
+
// Convert windows path to UNIX to avoid problems with "\"
String dir = PathUtils.normalizeFileSystemPath(dataDir.toString());
fwriter.write("dataDir=" + dir + "\n");
-
+
fwriter.write("clientPort=" + clientPort + "\n");
fwriter.flush();
fwriter.close();
@@ -75,7 +74,7 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
}
public void run() {
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
@@ -88,12 +87,15 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
public void shutdown() {
main.shutdown();
}
+
}
- public static class TestMain extends ZooKeeperServerMain {
+ public static class TestMain extends ZooKeeperServerMain {
+
public void shutdown() {
super.shutdown();
}
+
}
/**
@@ -107,11 +109,11 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
- Assert.assertEquals(SyncRequestProcessor.getSnapCount(), 2);
+ assertEquals(SyncRequestProcessor.getSnapCount(), 2);
main.shutdown();
@@ -120,4 +122,5 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
public void process(WatchedEvent event) {
// ignore for this test
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
index 97ad7923e..d3989ca47 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,10 +19,8 @@
package org.apache.zookeeper.server;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.RandomAccessFile;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
@@ -37,8 +35,8 @@ import org.slf4j.LoggerFactory;
* snapshot.
*/
public class InvalidSnapshotTest extends ClientBase {
- private static final Logger LOG =
- LoggerFactory.getLogger(InvalidSnapshotTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(InvalidSnapshotTest.class);
public InvalidSnapshotTest() {
SyncRequestProcessor.setSnapCount(100);
@@ -53,13 +51,12 @@ public class InvalidSnapshotTest extends ClientBase {
ZooKeeper zk = createClient();
try {
for (int i = 0; i < 2000; i++) {
- zk.create("/invalidsnap-" + i, new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
- NIOServerCnxnFactory factory = (NIOServerCnxnFactory)serverFactory;
+ NIOServerCnxnFactory factory = (NIOServerCnxnFactory) serverFactory;
stopServer();
// now corrupt the snapshot
@@ -75,10 +72,10 @@ public class InvalidSnapshotTest extends ClientBase {
// verify that the expected data exists and wasn't lost
zk = createClient();
try {
- assertTrue("the node should exist",
- (zk.exists("/invalidsnap-1999", false) != null));
+ assertTrue("the node should exist", (zk.exists("/invalidsnap-1999", false) != null));
} finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java
index 40eab0a81..7fc1a1693 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,16 +18,15 @@
package org.apache.zookeeper.server;
+import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
-import java.io.IOException;
import org.apache.zookeeper.server.NIOServerCnxnFactory.SelectorThread;
public class MockNIOServerCnxn extends NIOServerCnxn {
- public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock,
- SelectionKey sk, NIOServerCnxnFactory factory,
- SelectorThread selectorThread) throws IOException {
+ public MockNIOServerCnxn(
+ ZooKeeperServer zk, SocketChannel sock, SelectionKey sk, NIOServerCnxnFactory factory, SelectorThread selectorThread) throws IOException {
super(zk, sock, sk, factory, selectorThread);
}
@@ -42,4 +41,5 @@ public class MockNIOServerCnxn extends NIOServerCnxn {
protected boolean isSocketOpen() {
return true;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java
index db66bc9e8..2871932f6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -22,6 +22,7 @@ import java.io.IOException;
import java.nio.channels.SelectionKey;
public class MockSelectorThread extends NIOServerCnxnFactory.SelectorThread {
+
public MockSelectorThread(NIOServerCnxnFactory fact) throws IOException {
fact.super(0);
}
@@ -29,4 +30,5 @@ public class MockSelectorThread extends NIOServerCnxnFactory.SelectorThread {
public boolean addInterestOpsUpdateRequest(SelectionKey sk) {
return super.addInterestOpsUpdateRequest(sk);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java
index eb10720f0..831454540 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,6 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
import java.io.IOException;
@@ -23,10 +24,11 @@ import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import org.apache.jute.Record;
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.proto.ReplyHeader;
public class MockServerCnxn extends ServerCnxn {
+
public Certificate[] clientChain;
public boolean secure;
@@ -44,8 +46,7 @@ public class MockServerCnxn extends ServerCnxn {
}
@Override
- public void sendResponse(ReplyHeader h, Record r, String tag, String cacheKey, Stat stat)
- throws IOException {
+ public void sendResponse(ReplyHeader h, Record r, String tag, String cacheKey, Stat stat) throws IOException {
}
@Override
@@ -115,4 +116,5 @@ public class MockServerCnxn extends ServerCnxn {
public int getInterestOps() {
return 0;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
index 0426e2293..6e35d2c57 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,18 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -32,19 +44,12 @@ import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumZooKeeperServer;
import org.apache.zookeeper.server.quorum.UpgradeableSessionTracker;
import org.apache.zookeeper.test.QuorumBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
public class MultiOpSessionUpgradeTest extends QuorumBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(MultiOpSessionUpgradeTest.class);
@Override
@@ -63,9 +68,9 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());
- Assert.assertNotNull("unable to find server interlocutor", server);
- UpgradeableSessionTracker sessionTracker = (UpgradeableSessionTracker)server.getSessionTracker();
- Assert.assertFalse("session already global", sessionTracker.isGlobalSession(zk.getSessionId()));
+ assertNotNull("unable to find server interlocutor", server);
+ UpgradeableSessionTracker sessionTracker = (UpgradeableSessionTracker) server.getSessionTracker();
+ assertFalse("session already global", sessionTracker.isGlobalSession(zk.getSessionId()));
List<OpResult> multi = null;
try {
@@ -73,19 +78,18 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
Op.setData(path, data.getBytes(), 0),
Op.create(path + "/e", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL),
Op.create(path + "/p", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create(path + "/q", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)
- ));
+ Op.create(path + "/q", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)));
} catch (KeeperException.SessionExpiredException e) {
// the scenario that inspired this unit test
- Assert.fail("received session expired for a session promotion in a multi-op");
+ fail("received session expired for a session promotion in a multi-op");
}
- Assert.assertNotNull(multi);
- Assert.assertEquals(4, multi.size());
- Assert.assertEquals(data, new String(zk.getData(path + "/e", false, null)));
- Assert.assertEquals(data, new String(zk.getData(path + "/p", false, null)));
- Assert.assertEquals(data, new String(zk.getData(path + "/q", false, null)));
- Assert.assertTrue("session not promoted", sessionTracker.isGlobalSession(zk.getSessionId()));
+ assertNotNull(multi);
+ assertEquals(4, multi.size());
+ assertEquals(data, new String(zk.getData(path + "/e", false, null)));
+ assertEquals(data, new String(zk.getData(path + "/p", false, null)));
+ assertEquals(data, new String(zk.getData(path + "/q", false, null)));
+ assertTrue("session not promoted", sessionTracker.isGlobalSession(zk.getSessionId()));
}
@Test
@@ -96,14 +100,13 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());
- Assert.assertNotNull("unable to find server interlocutor", server);
+ assertNotNull("unable to find server interlocutor", server);
Request readRequest = makeGetDataRequest(path, zk.getSessionId());
Request createRequest = makeCreateRequest(path + "/e", zk.getSessionId());
- Assert.assertNull("tried to upgrade on a read", server.checkUpgradeSession(readRequest));
- Assert.assertNotNull("failed to upgrade on a create", server.checkUpgradeSession(createRequest));
- Assert.assertNull("tried to upgrade after successful promotion",
- server.checkUpgradeSession(createRequest));
+ assertNull("tried to upgrade on a read", server.checkUpgradeSession(readRequest));
+ assertNotNull("failed to upgrade on a create", server.checkUpgradeSession(createRequest));
+ assertNull("tried to upgrade after successful promotion", server.checkUpgradeSession(createRequest));
}
private Request makeGetDataRequest(String path, long sessionId) throws IOException {
@@ -118,8 +121,7 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
private Request makeCreateRequest(String path, long sessionId) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- CreateRequest createRequest = new CreateRequest(path,
- "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
+ CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<Id>());
@@ -128,9 +130,10 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
private QuorumZooKeeperServer getConnectedServer(long sessionId) {
for (QuorumPeer peer : getPeerList()) {
if (peer.getActiveServer().getSessionTracker().isTrackingSession(sessionId)) {
- return (QuorumZooKeeperServer)peer.getActiveServer();
+ return (QuorumZooKeeperServer) peer.getActiveServer();
}
}
return null;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
index 802065792..715c15a83 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,17 +18,17 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.PortAssignment;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
+import org.apache.zookeeper.PortAssignment;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class NIOServerCnxnFactoryTest {
+
private InetSocketAddress listenAddress;
private NIOServerCnxnFactory factory;
@@ -65,4 +65,5 @@ public class NIOServerCnxnFactoryTest {
ServerSocket ss = new ServerSocket(listenAddress.getPort());
ss.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
index 8795785e5..fc917e09b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,52 +15,45 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
-
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.quorum.BufferStats;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
public class NIOServerCnxnTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NIOServerCnxnTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(NIOServerCnxnTest.class);
/**
* Test operations on ServerCnxn after socket closure.
*/
@Test(timeout = 60000)
- public void testOperationsAfterCnxnClose() throws IOException,
- InterruptedException, KeeperException {
+ public void testOperationsAfterCnxnClose() throws IOException, InterruptedException, KeeperException {
final ZooKeeper zk = createClient();
final String path = "/a";
try {
// make sure zkclient works
- zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- assertNotNull("Didn't create znode:" + path,
- zk.exists(path, false));
+ zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertNotNull("Didn't create znode:" + path, zk.exists(path, false));
// Defaults ServerCnxnFactory would be instantiated with
// NIOServerCnxnFactory
- Assert.assertTrue(
- "Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!",
- serverFactory instanceof NIOServerCnxnFactory);
+ assertTrue("Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!", serverFactory instanceof NIOServerCnxnFactory);
Iterable<ServerCnxn> connections = serverFactory.getConnections();
for (ServerCnxn serverCnxn : connections) {
serverCnxn.close(ServerCnxn.DisconnectReason.CHANNEL_CLOSED_EXCEPTION);
@@ -68,8 +61,7 @@ public class NIOServerCnxnTest extends ClientBase {
serverCnxn.toString();
} catch (Exception e) {
LOG.error("Exception while getting connection details!", e);
- Assert.fail("Shouldn't throw exception while "
- + "getting connection details!");
+ fail("Shouldn't throw exception while " + "getting connection details!");
}
}
} finally {
@@ -82,14 +74,12 @@ public class NIOServerCnxnTest extends ClientBase {
public void testClientResponseStatsUpdate() throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats();
- assertThat("Last client response size should be initialized with INIT_VALUE",
- clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
+ assertThat("Last client response size should be initialized with INIT_VALUE", clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
- zk.create("/a", "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- assertThat("Last client response size should be greater then zero after client request was performed",
- clientResponseStats.getLastBufferSize(), greaterThan(0));
+ assertThat("Last client response size should be greater then zero after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
index 1ce7e055d..646d2051f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,22 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.IOException;
+import java.net.ProtocolException;
+import java.nio.charset.StandardCharsets;
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -25,41 +41,25 @@ import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.ClientX509Util;
import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.test.TestByteBufAllocator;
import org.apache.zookeeper.server.quorum.BufferStats;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.SSLAuthTest;
-import org.junit.Assert;
+import org.apache.zookeeper.test.TestByteBufAllocator;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.net.ProtocolException;
-import java.nio.charset.StandardCharsets;
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertThat;
-
/**
* Test verifies the behavior of NettyServerCnxn which represents a connection
* from a client to the server.
*/
public class NettyServerCnxnTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NettyServerCnxnTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(NettyServerCnxnTest.class);
@Override
public void setUp() throws Exception {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
NettyServerCnxnFactory.setTestAllocator(TestByteBufAllocator.getInstance());
super.maxCnxns = 1;
super.exceptionOnFailedConnect = true;
@@ -83,24 +83,19 @@ public class NettyServerCnxnTest extends ClientBase {
*/
@Test(timeout = 40000)
public void testSendCloseSession() throws Exception {
- Assert.assertTrue(
- "Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!",
- serverFactory instanceof NettyServerCnxnFactory);
+ assertTrue("Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!", serverFactory instanceof NettyServerCnxnFactory);
final ZooKeeper zk = createClient();
final ZooKeeperServer zkServer = serverFactory.getZooKeeperServer();
final String path = "/a";
try {
// make sure zkclient works
- zk.create(path, "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// set on watch
- Assert.assertNotNull("Didn't create znode:" + path,
- zk.exists(path, true));
- Assert.assertEquals(1, zkServer.getZKDatabase().getDataTree().getWatchCount());
+ assertNotNull("Didn't create znode:" + path, zk.exists(path, true));
+ assertEquals(1, zkServer.getZKDatabase().getDataTree().getWatchCount());
Iterable<ServerCnxn> connections = serverFactory.getConnections();
- Assert.assertEquals("Mismatch in number of live connections!", 1,
- serverFactory.getNumAliveConnections());
+ assertEquals("Mismatch in number of live connections!", 1, serverFactory.getNumAliveConnections());
for (ServerCnxn serverCnxn : connections) {
serverCnxn.sendCloseSession();
}
@@ -110,11 +105,11 @@ public class NettyServerCnxnTest extends ClientBase {
Thread.sleep(1000);
timeout += 1000;
if (timeout > CONNECTION_TIMEOUT) {
- Assert.fail("The number of live connections should be 0");
+ fail("The number of live connections should be 0");
}
}
// make sure the watch is removed when the connection closed
- Assert.assertEquals(0, zkServer.getZKDatabase().getDataTree().getWatchCount());
+ assertEquals(0, zkServer.getZKDatabase().getDataTree().getWatchCount());
} finally {
zk.close();
}
@@ -127,12 +122,9 @@ public class NettyServerCnxnTest extends ClientBase {
*/
@Test(timeout = 40000, expected = ProtocolException.class)
public void testMaxConnectionPerIpSurpased() throws Exception {
- Assert.assertTrue(
- "Did not instantiate ServerCnxnFactory with NettyServerCnxnFactory!",
- serverFactory instanceof NettyServerCnxnFactory);
+ assertTrue("Did not instantiate ServerCnxnFactory with NettyServerCnxnFactory!", serverFactory instanceof NettyServerCnxnFactory);
- try (final ZooKeeper zk1 = createClient();
- final ZooKeeper zk2 = createClient();) {
+ try (final ZooKeeper zk1 = createClient(); final ZooKeeper zk2 = createClient()) {
}
}
@@ -140,14 +132,11 @@ public class NettyServerCnxnTest extends ClientBase {
public void testClientResponseStatsUpdate() throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats();
- assertThat("Last client response size should be initialized with INIT_VALUE",
- clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
+ assertThat("Last client response size should be initialized with INIT_VALUE", clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
- zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- assertThat("Last client response size should be greater than 0 after client request was performed",
- clientResponseStats.getLastBufferSize(), greaterThan(0));
+ assertThat("Last client response size should be greater than 0 after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
byte[] contents = zk.getData("/a", null, null);
assertArrayEquals("unexpected data", "test".getBytes(StandardCharsets.UTF_8), contents);
@@ -158,14 +147,11 @@ public class NettyServerCnxnTest extends ClientBase {
public void testServerSideThrottling() throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats();
- assertThat("Last client response size should be initialized with INIT_VALUE",
- clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
+ assertThat("Last client response size should be initialized with INIT_VALUE", clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
- zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- assertThat("Last client response size should be greater than 0 after client request was performed",
- clientResponseStats.getLastBufferSize(), greaterThan(0));
+ assertThat("Last client response size should be greater than 0 after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
for (final ServerCnxn cnxn : serverFactory.cnxns) {
final NettyServerCnxn nettyCnxn = ((NettyServerCnxn) cnxn);
@@ -306,8 +292,7 @@ public class NettyServerCnxnTest extends ClientBase {
while (requestIssued++ < totalRequestsNum) {
zk.getData(path, null, new DataCallback() {
@Override
- public void processResult(int rc, String path,
- Object ctx, byte data[], Stat stat) {
+ public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
if (rc == 0) {
successResponse.addAndGet(1);
} else {
@@ -323,7 +308,7 @@ public class NettyServerCnxnTest extends ClientBase {
LOG.info("started thread to issue {} async requests", totalRequestsNum);
// and verify the response received is same as what we issued
- Assert.assertTrue(responseReceivedLatch.await(60, TimeUnit.SECONDS));
+ assertTrue(responseReceivedLatch.await(60, TimeUnit.SECONDS));
LOG.info("received all {} responses", totalRequestsNum);
stopped.set(true);
@@ -333,7 +318,7 @@ public class NettyServerCnxnTest extends ClientBase {
// wait another second for the left requests to finish
LOG.info("waiting another 1s for the requests to go through");
Thread.sleep(1000);
- Assert.assertEquals(successResponse.get(), totalRequestsNum);
+ assertEquals(successResponse.get(), totalRequestsNum);
}
} finally {
if (secure) {
@@ -341,4 +326,5 @@ public class NettyServerCnxnTest extends ClientBase {
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
index 4761c0045..4a2fb695a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,16 +18,15 @@
package org.apache.zookeeper.server;
-import java.util.Set;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
import java.util.Map;
-
+import java.util.Set;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.data.StatPersisted;
import org.apache.zookeeper.server.util.DigestCalculator;
-
import org.junit.After;
import org.junit.Before;
-import org.junit.Assert;
import org.junit.Test;
public class NodeHashMapImplTest extends ZKTestCase {
@@ -49,42 +48,42 @@ public class NodeHashMapImplTest extends ZKTestCase {
public void testOperations() {
NodeHashMapImpl nodes = new NodeHashMapImpl();
- Assert.assertEquals(0, nodes.size());
- Assert.assertEquals(0L, nodes.getDigest());
+ assertEquals(0, nodes.size());
+ assertEquals(0L, nodes.getDigest());
// add a new node
String p1 = "p1";
DataNode n1 = new DataNode(p1.getBytes(), 0L, new StatPersisted());
nodes.put(p1, n1);
- Assert.assertEquals(n1, nodes.get(p1));
- Assert.assertNotEquals(0L, nodes.getDigest());
- Assert.assertEquals(1, nodes.size());
+ assertEquals(n1, nodes.get(p1));
+ assertNotEquals(0L, nodes.getDigest());
+ assertEquals(1, nodes.size());
// put another node
String p2 = "p2";
nodes.put(p2, new DataNode(p2.getBytes(), 0L, new StatPersisted()));
Set<Map.Entry<String, DataNode>> entries = nodes.entrySet();
- Assert.assertEquals(2, entries.size());
+ assertEquals(2, entries.size());
// remove a node
nodes.remove(p1);
- Assert.assertEquals(1, nodes.size());
+ assertEquals(1, nodes.size());
nodes.remove(p2);
- Assert.assertEquals(0, nodes.size());
- Assert.assertEquals(0L, nodes.getDigest());
+ assertEquals(0, nodes.size());
+ assertEquals(0L, nodes.getDigest());
// test preChange and postChange
String p3 = "p3";
DataNode n3 = new DataNode(p3.getBytes(), 0L, new StatPersisted());
nodes.put(p3, n3);
long preChangeDigest = nodes.getDigest();
- Assert.assertNotEquals(0L, preChangeDigest);
+ assertNotEquals(0L, preChangeDigest);
nodes.preChange(p3, n3);
- Assert.assertEquals(0L, nodes.getDigest());
+ assertEquals(0L, nodes.getDigest());
n3.stat.setMzxid(1);
n3.stat.setMtime(1);
@@ -92,7 +91,8 @@ public class NodeHashMapImplTest extends ZKTestCase {
nodes.postChange(p3, n3);
long postChangeDigest = nodes.getDigest();
- Assert.assertNotEquals(0, postChangeDigest);
- Assert.assertNotEquals(preChangeDigest, postChangeDigest);
+ assertNotEquals(0, postChangeDigest);
+ assertNotEquals(preChangeDigest, postChangeDigest);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
index 9a130f09c..7aa74d321 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,9 +18,33 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
-import org.apache.zookeeper.*;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.StatPersisted;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.proto.DeleteRequest;
@@ -28,29 +52,13 @@ import org.apache.zookeeper.proto.SetDataRequest;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.*;
-
public class PrepRequestProcessorMetricsTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(PrepRequestProcessorMetricsTest.class);
ZooKeeperServer zks;
@@ -88,21 +96,21 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
record.serialize(boa, "request");
baos.close();
- return new Request(null, 1l, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), null);
+ return new Request(null, 1L, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), null);
}
private Request createRequest(String path, int opCode) throws IOException {
Record record;
switch (opCode) {
- case ZooDefs.OpCode.setData:
- record = new SetDataRequest(path, new byte[0], -1);
- break;
- case ZooDefs.OpCode.delete:
- record = new DeleteRequest(path, -1);
- break;
- default:
- record = new DeleteRequest(path, -1);
- break;
+ case ZooDefs.OpCode.setData:
+ record = new SetDataRequest(path, new byte[0], -1);
+ break;
+ case ZooDefs.OpCode.delete:
+ record = new DeleteRequest(path, -1);
+ break;
+ default:
+ record = new DeleteRequest(path, -1);
+ break;
}
return createRequest(record, opCode);
@@ -117,7 +125,8 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
CountDownLatch threeRequests = new CountDownLatch(3);
doAnswer(invocationOnMock -> {
threeRequests.countDown();
- return null;}).when(nextProcessor).processRequest(any(Request.class));
+ return null;
+ }).when(nextProcessor).processRequest(any(Request.class));
PrepRequestProcessor prepRequestProcessor = new PrepRequestProcessor(zks, nextProcessor);
@@ -129,7 +138,7 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
prepRequestProcessor.processRequest(createRequest(2, ZooDefs.OpCode.closeSession));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(3L, values.get("prep_processor_request_queued"));
+ assertEquals(3L, values.get("prep_processor_request_queued"));
// the sleep is just to make sure the requests will stay in the queue for some time
Thread.sleep(20);
@@ -138,21 +147,22 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
threeRequests.await(500, TimeUnit.MILLISECONDS);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(3L, values.get("max_prep_processor_queue_size"));
+ assertEquals(3L, values.get("max_prep_processor_queue_size"));
- Assert.assertThat((long)values.get("min_prep_processor_queue_time_ms"), greaterThan(20l));
- Assert.assertEquals(3L, values.get("cnt_prep_processor_queue_time_ms"));
+ assertThat((long) values.get("min_prep_processor_queue_time_ms"), greaterThan(20L));
+ assertEquals(3L, values.get("cnt_prep_processor_queue_time_ms"));
- Assert.assertEquals(3L, values.get("cnt_prep_process_time"));
- Assert.assertThat((long)values.get("max_prep_process_time"), greaterThan(0l));
+ assertEquals(3L, values.get("cnt_prep_process_time"));
+ assertThat((long) values.get("max_prep_process_time"), greaterThan(0L));
- Assert.assertEquals(1L, values.get("cnt_close_session_prep_time"));
- Assert.assertThat((long)values.get("max_close_session_prep_time"), greaterThanOrEqualTo(0L));
+ assertEquals(1L, values.get("cnt_close_session_prep_time"));
+ assertThat((long) values.get("max_close_session_prep_time"), greaterThanOrEqualTo(0L));
- Assert.assertEquals(5L, values.get("outstanding_changes_queued"));
+ assertEquals(5L, values.get("outstanding_changes_queued"));
}
private class SimpleWatcher implements Watcher {
+
CountDownLatch created;
public SimpleWatcher(CountDownLatch latch) {
this.created = latch;
@@ -161,6 +171,7 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
public void process(WatchedEvent e) {
created.countDown();
}
+
}
@Test
@@ -179,8 +190,9 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
created.await(200, TimeUnit.MILLISECONDS);
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertThat((long)values.get("outstanding_changes_removed"), greaterThan(0L));
+ assertThat((long) values.get("outstanding_changes_removed"), greaterThan(0L));
util.shutdownAll();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
index 04d8df475..8aacaac4e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,22 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException;
@@ -34,26 +50,13 @@ import org.apache.zookeeper.server.ZooKeeperServer.ChangeRecord;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.ErrorTxn;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
public class PrepRequestProcessorTest extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(PrepRequestProcessorTest.class);
private static final int CONNECTION_TIMEOUT = 3000;
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
@@ -74,8 +77,7 @@ public class PrepRequestProcessorTest extends ClientBase {
servcnxnf = ServerCnxnFactory.createFactory(PORT, -1);
servcnxnf.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
zks.sessionTracker = new MySessionTracker();
}
@@ -93,12 +95,11 @@ public class PrepRequestProcessorTest extends ClientBase {
public void testPRequest() throws Exception {
pLatch = new CountDownLatch(1);
processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
- Request foo = new Request(null, 1l, 1, OpCode.create, ByteBuffer.allocate(3), null);
+ Request foo = new Request(null, 1L, 1, OpCode.create, ByteBuffer.allocate(3), null);
processor.pRequest(foo);
- Assert.assertEquals("Request should have marshalling error", new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()),
- outcome.getTxn());
- Assert.assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+ assertEquals("Request should have marshalling error", new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()), outcome.getTxn());
+ assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
}
private Request createRequest(Record record, int opCode) throws IOException {
@@ -109,7 +110,7 @@ public class PrepRequestProcessorTest extends ClientBase {
baos.close();
// Id
List<Id> ids = Arrays.asList(Ids.ANYONE_ID_UNSAFE);
- return new Request(null, 1l, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), ids);
+ return new Request(null, 1L, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), ids);
}
private void process(List<Op> ops) throws Exception {
@@ -120,7 +121,7 @@ public class PrepRequestProcessorTest extends ClientBase {
Request req = createRequest(record, OpCode.multi);
processor.pRequest(req);
- Assert.assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+ assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
}
/**
@@ -131,30 +132,23 @@ public class PrepRequestProcessorTest extends ClientBase {
public void testMultiOutstandingChange() throws Exception {
zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
+ assertNull(zks.outstandingChangesForPath.get("/foo"));
- process(Arrays.asList(
- Op.setData("/foo", new byte[0], -1)));
+ process(Arrays.asList(Op.setData("/foo", new byte[0], -1)));
ChangeRecord cr = zks.outstandingChangesForPath.get("/foo");
- Assert.assertNotNull("Change record wasn't set", cr);
- Assert.assertEquals("Record zxid wasn't set correctly",
- 1, cr.zxid);
+ assertNotNull("Change record wasn't set", cr);
+ assertEquals("Record zxid wasn't set correctly", 1, cr.zxid);
- process(Arrays.asList(
- Op.delete("/foo", -1)));
+ process(Arrays.asList(Op.delete("/foo", -1)));
cr = zks.outstandingChangesForPath.get("/foo");
- Assert.assertEquals("Record zxid wasn't set correctly",
- 2, cr.zxid);
-
+ assertEquals("Record zxid wasn't set correctly", 2, cr.zxid);
// It should fail and shouldn't change outstanding record.
- process(Arrays.asList(
- Op.delete("/foo", -1)));
+ process(Arrays.asList(Op.delete("/foo", -1)));
cr = zks.outstandingChangesForPath.get("/foo");
// zxid should still be previous result because record's not changed.
- Assert.assertEquals("Record zxid wasn't set correctly",
- 2, cr.zxid);
+ assertEquals("Record zxid wasn't set correctly", 2, cr.zxid);
}
/**
@@ -168,17 +162,15 @@ public class PrepRequestProcessorTest extends ClientBase {
zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
zks.getZKDatabase().dataTree.createNode("/foo/bar", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
+ assertNull(zks.outstandingChangesForPath.get("/foo"));
// multi record:
// set "/foo" => succeed, leave a outstanding change
// delete "/foo" => fail, roll back change
- process(Arrays.asList(
- Op.setData("/foo", new byte[0], -1),
- Op.delete("/foo", -1)));
+ process(Arrays.asList(Op.setData("/foo", new byte[0], -1), Op.delete("/foo", -1)));
// aborting multi shouldn't leave any record.
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
+ assertNull(zks.outstandingChangesForPath.get("/foo"));
}
/**
@@ -194,11 +186,12 @@ public class PrepRequestProcessorTest extends ClientBase {
Request req = createRequest(record, OpCode.setData);
processor.pRequest(req);
pLatch.await();
- Assert.assertEquals(outcome.getHdr().getType(), OpCode.error);
- Assert.assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
+ assertEquals(outcome.getHdr().getType(), OpCode.error);
+ assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
}
private class MyRequestProcessor implements RequestProcessor {
+
@Override
public void processRequest(Request request) {
// getting called by PrepRequestProcessor
@@ -210,9 +203,11 @@ public class PrepRequestProcessorTest extends ClientBase {
// TODO Auto-generated method stub
}
+
}
private class MySessionTracker implements SessionTracker {
+
@Override
public boolean trackSession(long id, int to) {
// TODO Auto-generated method stub
@@ -224,8 +219,7 @@ public class PrepRequestProcessorTest extends ClientBase {
return false;
}
@Override
- public void checkSession(long sessionId, Object owner)
- throws SessionExpiredException, SessionMovedException {
+ public void checkSession(long sessionId, Object owner) throws SessionExpiredException, SessionMovedException {
// TODO Auto-generated method stub
}
@Override
@@ -238,18 +232,17 @@ public class PrepRequestProcessorTest extends ClientBase {
// TODO Auto-generated method stub
}
- @Override
+ @Override
public void removeSession(long sessionId) {
// TODO Auto-generated method stub
}
public int upgradeSession(long sessionId) {
- // TODO Auto-generated method stub
- return 0;
+ // TODO Auto-generated method stub
+ return 0;
}
@Override
- public void setOwner(long id, Object owner)
- throws SessionExpiredException {
+ public void setOwner(long id, Object owner) throws SessionExpiredException {
// TODO Auto-generated method stub
}
@@ -265,7 +258,7 @@ public class PrepRequestProcessorTest extends ClientBase {
}
@Override
public void setSessionClosing(long sessionId) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
@Override
public boolean isTrackingSession(long sessionId) {
@@ -273,8 +266,7 @@ public class PrepRequestProcessorTest extends ClientBase {
return false;
}
@Override
- public void checkGlobalSession(long sessionId, Object owner)
- throws SessionExpiredException, SessionMovedException {
+ public void checkGlobalSession(long sessionId, Object owner) throws SessionExpiredException, SessionMovedException {
// TODO Auto-generated method stub
}
@Override
@@ -285,5 +277,7 @@ public class PrepRequestProcessorTest extends ClientBase {
public long getLocalSessionCount() {
return 0;
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
index 7898e6eaa..f9c3091d5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,7 +19,10 @@
package org.apache.zookeeper.server;
import static org.junit.Assert.assertEquals;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -29,27 +32,22 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.zookeeper.data.Stat;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.server.PurgeTxnLog;
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.SyncRequestProcessor;
-import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PurgeTxnTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(PurgeTxnTest.class);
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private static final int CONNECTION_TIMEOUT = 3000;
@@ -76,32 +74,29 @@ public class PurgeTxnTest extends ZKTestCase {
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
- for (int i = 0; i< 2000; i++) {
- zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < 2000; i++) {
+ zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
f.shutdown();
zks.getTxnLogFactory().close();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
// now corrupt the snapshot
PurgeTxnLog.purge(tmpDir, tmpDir, 3);
FileTxnSnapLog snaplog = new FileTxnSnapLog(tmpDir, tmpDir);
List<File> listLogs = snaplog.findNRecentSnapshots(4);
int numSnaps = 0;
- for (File ff: listLogs) {
+ for (File ff : listLogs) {
if (ff.getName().startsWith("snapshot")) {
numSnaps++;
}
}
- Assert.assertTrue("exactly 3 snapshots ", (numSnaps == 3));
+ assertTrue("exactly 3 snapshots ", (numSnaps == 3));
snaplog.close();
zks.shutdown();
}
@@ -123,8 +118,7 @@ public class PurgeTxnTest extends ZKTestCase {
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
final ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
final CountDownLatch doPurge = new CountDownLatch(1);
final CountDownLatch purgeFinished = new CountDownLatch(1);
@@ -132,8 +126,7 @@ public class PurgeTxnTest extends ZKTestCase {
new Thread() {
public void run() {
try {
- doPurge.await(OP_TIMEOUT_IN_MILLIS / 2,
- TimeUnit.MILLISECONDS);
+ doPurge.await(OP_TIMEOUT_IN_MILLIS / 2, TimeUnit.MILLISECONDS);
PurgeTxnLog.purge(tmpDir, tmpDir, 3);
} catch (IOException ioe) {
LOG.error("Exception when purge", ioe);
@@ -144,20 +137,18 @@ public class PurgeTxnTest extends ZKTestCase {
} finally {
purgeFinished.countDown();
}
- };
+ }
}.start();
final int thCount = 3;
- List<String> znodes = manyClientOps(zk, doPurge, thCount,
- "/invalidsnap");
- Assert.assertTrue("Purging is not finished!", purgeFinished.await(
- OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
- Assert.assertFalse("Purging failed!", opFailed.get());
+ List<String> znodes = manyClientOps(zk, doPurge, thCount, "/invalidsnap");
+ assertTrue("Purging is not finished!", purgeFinished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
+ assertFalse("Purging failed!", opFailed.get());
for (String znode : znodes) {
try {
zk.getData(znode, false, null);
} catch (Exception ke) {
LOG.error("Unexpected exception when visiting znode!", ke);
- Assert.fail("Unexpected exception when visiting znode!");
+ fail("Unexpected exception when visiting znode!");
}
}
zk.close();
@@ -177,8 +168,7 @@ public class PurgeTxnTest extends ZKTestCase {
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
// Test that with no snaps, findNRecentSnapshots returns empty list
FileTxnSnapLog txnLog = new FileTxnSnapLog(tmpDir, tmpDir);
@@ -190,15 +180,12 @@ public class PurgeTxnTest extends ZKTestCase {
for (int i = 0; i < nRecentCount; i++) {
// simulate log file
File logFile = new File(version2 + "/log." + Long.toHexString(--counter));
- Assert.assertTrue("Failed to create log File:" + logFile.toString(),
- logFile.createNewFile());
+ assertTrue("Failed to create log File:" + logFile.toString(), logFile.createNewFile());
// simulate snapshot file
- File snapFile = new File(version2 + "/snapshot."
- + Long.toHexString(--counter));
- Assert.assertTrue("Failed to create snap File:" + snapFile.toString(),
- snapFile.createNewFile());
+ File snapFile = new File(version2 + "/snapshot." + Long.toHexString(--counter));
+ assertTrue("Failed to create snap File:" + snapFile.toString(), snapFile.createNewFile());
// add the n recent snap files for assertion
- if(i < nRecentSnap){
+ if (i < nRecentSnap) {
expectedNRecentSnapFiles.add(snapFile);
}
}
@@ -206,19 +193,17 @@ public class PurgeTxnTest extends ZKTestCase {
// Test that when we ask for recent snaps we get the number we asked for and
// the files we expected
List<File> nRecentSnapFiles = txnLog.findNRecentSnapshots(nRecentSnap);
- Assert.assertEquals("exactly 4 snapshots ", 4,
- nRecentSnapFiles.size());
+ assertEquals("exactly 4 snapshots ", 4, nRecentSnapFiles.size());
expectedNRecentSnapFiles.removeAll(nRecentSnapFiles);
- Assert.assertEquals("Didn't get the recent snap files", 0,
- expectedNRecentSnapFiles.size());
+ assertEquals("Didn't get the recent snap files", 0, expectedNRecentSnapFiles.size());
// Test that when asking for more snaps than we created, we still only get snaps
// not logs or anything else (per ZOOKEEPER-2420)
nRecentSnapFiles = txnLog.findNRecentSnapshots(nRecentCount + 5);
assertEquals(nRecentCount, nRecentSnapFiles.size());
- for (File f: nRecentSnapFiles) {
- Assert.assertTrue("findNRecentSnapshots() returned a non-snapshot: " + f.getPath(),
- (Util.getZxidFromName(f.getName(), "snapshot") != -1));
+ for (File f : nRecentSnapFiles) {
+ assertTrue("findNRecentSnapshots() returned a non-snapshot: "
+ + f.getPath(), (Util.getZxidFromName(f.getName(), "snapshot") != -1));
}
txnLog.close();
@@ -237,20 +222,17 @@ public class PurgeTxnTest extends ZKTestCase {
AtomicInteger offset = new AtomicInteger(0);
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
List<File> snapsToPurge = new ArrayList<File>();
List<File> logsToPurge = new ArrayList<File>();
List<File> snaps = new ArrayList<File>();
List<File> logs = new ArrayList<File>();
List<File> snapsAboveRecentFiles = new ArrayList<File>();
List<File> logsAboveRecentFiles = new ArrayList<File>();
- createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge,
- logsToPurge);
+ createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge, logsToPurge);
createDataDirFiles(offset, nRecentCount, false, version2, snaps, logs);
logs.add(logsToPurge.remove(0)); // log that precedes first retained snapshot is also retained
- createDataDirFiles(offset, fileAboveRecentCount, false, version2,
- snapsAboveRecentFiles, logsAboveRecentFiles);
+ createDataDirFiles(offset, fileAboveRecentCount, false, version2, snapsAboveRecentFiles, logsAboveRecentFiles);
/**
* The newest log file preceding the oldest retained snapshot is not removed as it may
@@ -292,8 +274,7 @@ public class PurgeTxnTest extends ZKTestCase {
AtomicInteger offset = new AtomicInteger(0);
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
List<File> snaps = new ArrayList<File>();
List<File> logs = new ArrayList<File>();
createDataDirFiles(offset, nRecentCount, testWithPrecedingLogFile, version2, snaps, logs);
@@ -316,14 +297,12 @@ public class PurgeTxnTest extends ZKTestCase {
AtomicInteger offset = new AtomicInteger(0);
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
List<File> snapsToPurge = new ArrayList<File>();
List<File> logsToPurge = new ArrayList<File>();
List<File> snaps = new ArrayList<File>();
List<File> logs = new ArrayList<File>();
- createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge,
- logsToPurge);
+ createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge, logsToPurge);
createDataDirFiles(offset, nRecentCount, false, version2, snaps, logs);
logs.add(logsToPurge.remove(0)); // log that precedes first retained snapshot is also retained
@@ -347,8 +326,7 @@ public class PurgeTxnTest extends ZKTestCase {
* verify these values are parsed properly and functionality works fine
*/
@Test
- public void testPurgeTxnLogWithDataDir()
- throws Exception {
+ public void testPurgeTxnLogWithDataDir() throws Exception {
tmpDir = ClientBase.createTmpDir();
File dataDir = new File(tmpDir, "dataDir");
File dataLogDir = new File(tmpDir, "dataLogDir");
@@ -365,20 +343,16 @@ public class PurgeTxnTest extends ZKTestCase {
// directories
for (int i = 0; i < totalFiles; i++) {
// simulate log file
- File logFile = new File(dataLogDirVersion2, "log."
- + Long.toHexString(i));
+ File logFile = new File(dataLogDirVersion2, "log." + Long.toHexString(i));
logFile.createNewFile();
// simulate snapshot file
- File snapFile = new File(dataDirVersion2, "snapshot."
- + Long.toHexString(i));
+ File snapFile = new File(dataDirVersion2, "snapshot." + Long.toHexString(i));
snapFile.createNewFile();
}
int numberOfSnapFilesToKeep = 10;
// scenario where four parameter are passed
- String[] args = new String[] { dataLogDir.getAbsolutePath(),
- dataDir.getAbsolutePath(), "-n",
- Integer.toString(numberOfSnapFilesToKeep) };
+ String[] args = new String[]{dataLogDir.getAbsolutePath(), dataDir.getAbsolutePath(), "-n", Integer.toString(numberOfSnapFilesToKeep)};
PurgeTxnLog.main(args);
assertEquals(numberOfSnapFilesToKeep, dataDirVersion2.listFiles().length);
@@ -393,8 +367,7 @@ public class PurgeTxnTest extends ZKTestCase {
* these values are parsed properly and functionality works fine
*/
@Test
- public void testPurgeTxnLogWithoutDataDir()
- throws Exception {
+ public void testPurgeTxnLogWithoutDataDir() throws Exception {
tmpDir = ClientBase.createTmpDir();
File dataDir = new File(tmpDir, "dataDir");
File dataLogDir = new File(tmpDir, "dataLogDir");
@@ -410,21 +383,20 @@ public class PurgeTxnTest extends ZKTestCase {
// create transaction and snapshot files in data directory
for (int i = 0; i < totalFiles; i++) {
// simulate log file
- File logFile = new File(dataLogDirVersion2, "log."
- + Long.toHexString(i));
+ File logFile = new File(dataLogDirVersion2, "log." + Long.toHexString(i));
logFile.createNewFile();
// simulate snapshot file
- File snapFile = new File(dataLogDirVersion2, "snapshot."
- + Long.toHexString(i));
+ File snapFile = new File(dataLogDirVersion2, "snapshot." + Long.toHexString(i));
snapFile.createNewFile();
}
int numberOfSnapFilesToKeep = 10;
// scenario where only three parameter are passed
- String[] args = new String[] { dataLogDir.getAbsolutePath(), "-n",
- Integer.toString(numberOfSnapFilesToKeep) };
+ String[] args = new String[]{dataLogDir.getAbsolutePath(), "-n", Integer.toString(numberOfSnapFilesToKeep)};
PurgeTxnLog.main(args);
- assertEquals(numberOfSnapFilesToKeep * 2, // Since for each snapshot we have a log file with same zxid, expect same # logs as snaps to be kept
+ assertEquals(
+ numberOfSnapFilesToKeep
+ * 2, // Since for each snapshot we have a log file with same zxid, expect same # logs as snaps to be kept
dataLogDirVersion2.listFiles().length);
ClientBase.recursiveDelete(tmpDir);
@@ -457,8 +429,7 @@ public class PurgeTxnTest extends ZKTestCase {
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
// Unique identifier for each znode that we create.
@@ -469,16 +440,14 @@ public class PurgeTxnTest extends ZKTestCase {
* snapshots. Do not rollover the log.
*/
for (int snapshotCount = 0; snapshotCount < SNAP_RETAIN_COUNT; snapshotCount++) {
- for (int i = 0; i< 100; i++, unique++) {
- zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < 100; i++, unique++) {
+ zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zks.takeSnapshot();
}
// Create some additional znodes without taking a snapshot afterwards.
- for (int i = 0; i< 100; i++, unique++) {
- zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < 100; i++, unique++) {
+ zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
@@ -488,8 +457,7 @@ public class PurgeTxnTest extends ZKTestCase {
f.shutdown();
zks.getTxnLogFactory().close();
zks.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
// Purge snapshot and log files.
PurgeTxnLog.purge(tmpDir, tmpDir, SNAP_RETAIN_COUNT);
@@ -508,7 +476,7 @@ public class PurgeTxnTest extends ZKTestCase {
*/
final String lastZnode = "/snap-" + (unique - 1);
final Stat stat = zk.exists(lastZnode, false);
- Assert.assertNotNull("Last znode does not exist: " + lastZnode, stat);
+ assertNotNull("Last znode does not exist: " + lastZnode, stat);
// Shutdown for the last time.
f.shutdown();
@@ -518,14 +486,11 @@ public class PurgeTxnTest extends ZKTestCase {
private File createDataDirLogFile(File version_2, int Zxid) throws IOException {
File logFile = new File(version_2 + "/log." + Long.toHexString(Zxid));
- Assert.assertTrue("Failed to create log File:" + logFile.toString(),
- logFile.createNewFile());
+ assertTrue("Failed to create log File:" + logFile.toString(), logFile.createNewFile());
return logFile;
}
- private void createDataDirFiles(AtomicInteger offset, int limit, boolean createPrecedingLogFile,
- File version_2, List<File> snaps, List<File> logs)
- throws IOException {
+ private void createDataDirFiles(AtomicInteger offset, int limit, boolean createPrecedingLogFile, File version_2, List<File> snaps, List<File> logs) throws IOException {
int counter = offset.get() + (2 * limit);
if (createPrecedingLogFile) {
counter++;
@@ -535,10 +500,8 @@ public class PurgeTxnTest extends ZKTestCase {
// simulate log file
logs.add(createDataDirLogFile(version_2, --counter));
// simulate snapshot file
- File snapFile = new File(version_2 + "/snapshot."
- + Long.toHexString(--counter));
- Assert.assertTrue("Failed to create snap File:" + snapFile.toString(),
- snapFile.createNewFile());
+ File snapFile = new File(version_2 + "/snapshot." + Long.toHexString(--counter));
+ assertTrue("Failed to create snap File:" + snapFile.toString(), snapFile.createNewFile());
snaps.add(snapFile);
}
if (createPrecedingLogFile) {
@@ -548,16 +511,13 @@ public class PurgeTxnTest extends ZKTestCase {
private void verifyFilesAfterPurge(List<File> logs, boolean exists) {
for (File file : logs) {
- Assert.assertEquals("After purging, file " + file, exists,
- file.exists());
+ assertEquals("After purging, file " + file, exists, file.exists());
}
}
- private List<String> manyClientOps(final ZooKeeper zk,
- final CountDownLatch doPurge, int thCount, final String prefix) {
+ private List<String> manyClientOps(final ZooKeeper zk, final CountDownLatch doPurge, int thCount, final String prefix) {
Thread[] ths = new Thread[thCount];
- final List<String> znodes = Collections
- .synchronizedList(new ArrayList<String>());
+ final List<String> znodes = Collections.synchronizedList(new ArrayList<String>());
final CountDownLatch finished = new CountDownLatch(thCount);
for (int indx = 0; indx < thCount; indx++) {
final String myprefix = prefix + "-" + indx;
@@ -567,8 +527,7 @@ public class PurgeTxnTest extends ZKTestCase {
try {
String mynode = myprefix + "-" + i;
znodes.add(mynode);
- zk.create(mynode, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(mynode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {
LOG.error("Unexpected exception occurred!", e);
}
@@ -577,7 +536,7 @@ public class PurgeTxnTest extends ZKTestCase {
}
}
finished.countDown();
- };
+ }
};
ths[indx] = th;
}
@@ -586,12 +545,12 @@ public class PurgeTxnTest extends ZKTestCase {
thread.start();
}
try {
- Assert.assertTrue("ZkClient ops is not finished!",
- finished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
+ assertTrue("ZkClient ops is not finished!", finished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
} catch (InterruptedException ie) {
LOG.error("Unexpected exception occurred!", ie);
- Assert.fail("Unexpected exception occurred!");
+ fail("Unexpected exception occurred!");
}
return znodes;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
index 795472f14..6bb5d954c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,24 +18,24 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.Test;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.*;
-
public class ReferenceCountedACLCacheTest {
+
@Test
public void testSameACLGivesSameID() {
List<ACL> testACL = createACL("myid");
@@ -195,7 +195,7 @@ public class ReferenceCountedACLCacheTest {
@Test
public void testNPEInDeserialize() throws IOException {
- ReferenceCountedACLCache serializeCache = new ReferenceCountedACLCache(){
+ ReferenceCountedACLCache serializeCache = new ReferenceCountedACLCache() {
@Override
public synchronized void serialize(OutputArchive oa) throws IOException {
oa.writeInt(1, "map");
@@ -211,15 +211,14 @@ public class ReferenceCountedACLCacheTest {
ReferenceCountedACLCache deserializedCache = new ReferenceCountedACLCache();
try {
deserializedCache.deserialize(inArchive);
- } catch (NullPointerException e){
+ } catch (NullPointerException e) {
fail("should not throw NPE while do deserialized");
} catch (RuntimeException e) {
// do nothing.
}
}
-
- private void assertCachesEqual(ReferenceCountedACLCache expected, ReferenceCountedACLCache actual){
+ private void assertCachesEqual(ReferenceCountedACLCache expected, ReferenceCountedACLCache actual) {
assertEquals(expected.aclIndex, actual.aclIndex);
assertEquals(expected.aclKeyMap, actual.aclKeyMap);
assertEquals(expected.longKeyMap, actual.longKeyMap);
@@ -272,7 +271,7 @@ public class ReferenceCountedACLCacheTest {
return -1L;
}
- for (int i = 0; i < num -1; i++) {
+ for (int i = 0; i < num - 1; i++) {
cache.convertAcls(acl);
}
@@ -284,4 +283,5 @@ public class ReferenceCountedACLCacheTest {
acl1.add(new ACL(ZooDefs.Perms.ADMIN, new Id("scheme", id)));
return acl1;
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
index 9eee9269c..db40d86fd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,40 +18,34 @@
package org.apache.zookeeper.server;
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.hamcrest.Matchers.lessThan;
-
public class RequestThrottlerTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(RequestThrottlerTest.class);
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private final static int TOTAL_REQUESTS = 5;
- private final static int STALL_TIME = 5000;
+ private static final int TOTAL_REQUESTS = 5;
+ private static final int STALL_TIME = 5000;
// latch to hold requests in the PrepRequestProcessor to
// keep them from going down the pipeline to reach the final
@@ -79,8 +73,7 @@ public class RequestThrottlerTest extends ZKTestCase {
f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
resumeProcess = null;
submitted = null;
@@ -107,6 +100,7 @@ public class RequestThrottlerTest extends ZKTestCase {
// 1. uses our version of PrepRequestProcessor, which can hold the request as long as we want
// 2. count the number of submitted requests
class TestZooKeeperServer extends ZooKeeperServer {
+
public TestZooKeeperServer(File snapDir, File logDir, int tickTime) throws IOException {
super(snapDir, logDir, tickTime);
}
@@ -114,8 +108,7 @@ public class RequestThrottlerTest extends ZKTestCase {
@Override
protected void setupRequestProcessors() {
RequestProcessor finalProcessor = new FinalRequestProcessor(this);
- RequestProcessor syncProcessor = new SyncRequestProcessor(this,
- finalProcessor);
+ RequestProcessor syncProcessor = new SyncRequestProcessor(this, finalProcessor);
((SyncRequestProcessor) syncProcessor).start();
firstProcessor = new TestPrepRequestProcessor(this, syncProcessor);
((TestPrepRequestProcessor) firstProcessor).start();
@@ -128,9 +121,11 @@ public class RequestThrottlerTest extends ZKTestCase {
}
super.submitRequest(si);
}
+
}
class TestPrepRequestProcessor extends PrepRequestProcessor {
+
public TestPrepRequestProcessor(ZooKeeperServer zks, RequestProcessor syncProcessor) {
super(zks, syncProcessor);
}
@@ -152,6 +147,7 @@ public class RequestThrottlerTest extends ZKTestCase {
super.pRequest(request);
}
+
}
@Test
@@ -170,9 +166,10 @@ public class RequestThrottlerTest extends ZKTestCase {
entered = new CountDownLatch(TOTAL_REQUESTS);
// send 5 requests asynchronously
- for (int i =0; i < TOTAL_REQUESTS; i++) {
- zk.create("/request_throttle_test- " + i , ("/request_throttle_test- " + i).getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {}, null);
+ for (int i = 0; i < TOTAL_REQUESTS; i++) {
+ zk.create("/request_throttle_test- " + i, ("/request_throttle_test- "
+ + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {
+ }, null);
}
// make sure the server received all 5 requests
@@ -180,8 +177,8 @@ public class RequestThrottlerTest extends ZKTestCase {
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
// but only two requests can get into the pipeline because of the throttler
- Assert.assertEquals(2L, (long)metrics.get("prep_processor_request_queued"));
- Assert.assertEquals(1L, (long)metrics.get("request_throttle_wait_count"));
+ assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+ assertEquals(1L, (long) metrics.get("request_throttle_wait_count"));
// let the requests go through the pipeline and the throttler will be waken up to allow more requests
// to enter the pipeline
@@ -189,7 +186,7 @@ public class RequestThrottlerTest extends ZKTestCase {
entered.await(STALL_TIME, TimeUnit.MILLISECONDS);
metrics = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(TOTAL_REQUESTS, (long)metrics.get("prep_processor_request_queued"));
+ assertEquals(TOTAL_REQUESTS, (long) metrics.get("prep_processor_request_queued"));
}
@Test
@@ -208,9 +205,10 @@ public class RequestThrottlerTest extends ZKTestCase {
submitted = new CountDownLatch(TOTAL_REQUESTS);
// send 5 requests asynchronously
- for (int i=0; i<TOTAL_REQUESTS; i++) {
- zk.create("/request_throttle_test- " + i , ("/request_throttle_test- " + i).getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {}, null);
+ for (int i = 0; i < TOTAL_REQUESTS; i++) {
+ zk.create("/request_throttle_test- " + i, ("/request_throttle_test- "
+ + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {
+ }, null);
}
// make sure the server received all 5 requests
@@ -218,10 +216,10 @@ public class RequestThrottlerTest extends ZKTestCase {
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
// but only two requests can get into the pipeline because of the throttler
- Assert.assertEquals(2L, (long)metrics.get("prep_processor_request_queued"));
- Assert.assertEquals(1L, (long)metrics.get("request_throttle_wait_count"));
+ assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+ assertEquals(1L, (long) metrics.get("request_throttle_wait_count"));
- for (ServerCnxn cnxn : f.cnxns){
+ for (ServerCnxn cnxn : f.cnxns) {
cnxn.setStale();
}
zk = null;
@@ -236,7 +234,8 @@ public class RequestThrottlerTest extends ZKTestCase {
// the rest of the 3 requests will be dropped
// but only the first one for a connection will be counted
metrics = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, (long)metrics.get("prep_processor_request_queued"));
- Assert.assertEquals(1, (long)metrics.get("stale_requests_dropped"));
+ assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+ assertEquals(1, (long) metrics.get("stale_requests_dropped"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
index 43982322d..5a0fbef72 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -20,25 +20,26 @@ package org.apache.zookeeper.server;
import java.io.IOException;
import java.io.OutputStream;
-
import org.apache.jute.BinaryOutputArchive;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SerializationPerfTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SerializationPerfTest.class);
private static class NullOutputStream extends OutputStream {
+
public void write(int b) {
// do nothing - exclude persistence from perf
}
+
}
- static int createNodes(DataTree tree, String path, int depth,
- int childcount, int parentCVersion, byte[] data) throws KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ static int createNodes(DataTree tree, String path, int depth, int childcount, int parentCVersion, byte[] data) throws KeeperException.NodeExistsException, KeeperException.NoNodeException {
path += "node" + depth;
tree.createNode(path, data, null, -1, ++parentCVersion, 1, 1);
@@ -56,70 +57,64 @@ public class SerializationPerfTest extends ZKTestCase {
return count;
}
- private static void serializeTree(int depth, int width, int len)
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ private static void serializeTree(int depth, int width, int len) throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
DataTree tree = new DataTree();
createNodes(tree, "/", depth, width, tree.getNode("/").stat.getCversion(), new byte[len]);
int count = tree.getNodeCount();
- BinaryOutputArchive oa =
- BinaryOutputArchive.getArchive(new NullOutputStream());
+ BinaryOutputArchive oa = BinaryOutputArchive.getArchive(new NullOutputStream());
System.gc();
long start = System.nanoTime();
tree.serialize(oa, "test");
long end = System.nanoTime();
- long durationms = (end - start)/1000000L;
- long pernodeus = ((end - start)/1000L)/count;
- LOG.info("Serialized " + count + " nodes in "
- + durationms + " ms (" + pernodeus + "us/node), depth="
- + depth + " width=" + width + " datalen=" + len);
+ long durationms = (end - start) / 1000000L;
+ long pernodeus = ((end - start) / 1000L) / count;
+ LOG.info("Serialized "
+ + count + " nodes in "
+ + durationms + " ms ("
+ + pernodeus + "us/node), depth=" + depth
+ + " width=" + width
+ + " datalen=" + len);
}
@Test
- public void testSingleSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testSingleSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(1, 0, 20);
}
@Test
- public void testWideSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testWideSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(2, 10000, 20);
}
@Test
- public void testDeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testDeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(400, 1, 20);
}
@Test
- public void test10Wide5DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test10Wide5DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(5, 10, 20);
}
@Test
- public void test15Wide5DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test15Wide5DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(5, 15, 20);
}
@Test
- public void test25Wide4DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test25Wide4DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(4, 25, 20);
}
@Test
- public void test40Wide4DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test40Wide4DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(4, 40, 20);
}
@Test
- public void test300Wide3DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test300Wide3DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(3, 300, 20);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
index a04c37b35..3f3f4964a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.fail;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
@@ -26,21 +29,19 @@ import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import java.util.ArrayList;
-import java.util.List;
-
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class ServerIdTest extends ClientBase {
+
private final TestType testType;
private static class TestType {
+
final boolean ttlsEnabled;
final int serverId;
@@ -48,13 +49,14 @@ public class ServerIdTest extends ClientBase {
this.ttlsEnabled = ttlsEnabled;
this.serverId = serverId;
}
+
}
@Parameterized.Parameters
public static List<TestType> data() {
List<TestType> testTypes = new ArrayList<>();
- for ( boolean ttlsEnabled : new boolean[]{true, false} ) {
- for ( int serverId = 0; serverId <= 255; ++serverId ) {
+ for (boolean ttlsEnabled : new boolean[]{true, false}) {
+ for (int serverId = 0; serverId <= 255; ++serverId) {
testTypes.add(new TestType(ttlsEnabled, serverId));
}
}
@@ -80,7 +82,7 @@ public class ServerIdTest extends ClientBase {
try {
super.setUpWithServerId(testType.serverId);
} catch (RuntimeException e) {
- if ( testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID) ) {
+ if (testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
return; // expected
}
throw e;
@@ -89,7 +91,7 @@ public class ServerIdTest extends ClientBase {
@Test
public void doTest() throws Exception {
- if ( testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID) ) {
+ if (testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
return;
}
@@ -100,20 +102,21 @@ public class ServerIdTest extends ClientBase {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo", -1);
- if ( testType.ttlsEnabled ) {
+ if (testType.ttlsEnabled) {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 1000); // should work
} else {
try {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 1000);
- Assert.fail("Should have thrown KeeperException.UnimplementedException");
+ fail("Should have thrown KeeperException.UnimplementedException");
} catch (KeeperException.UnimplementedException e) {
// expected
}
}
} finally {
- if ( zk != null ) {
+ if (zk != null) {
zk.close();
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
index a71b3e26d..29a9fd96b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,17 +18,17 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.ThreadLocalRandom;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.metric.AvgMinMaxCounter;
import org.apache.zookeeper.server.metric.SimpleCounter;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.concurrent.ThreadLocalRandom;
-
public class ServerMetricsTest extends ZKTestCase {
+
private static final int RANDOM_TRIALS = 100;
private static final int RANDOM_SIZE = 100;
@@ -67,17 +67,17 @@ public class ServerMetricsTest extends ZKTestCase {
long expectedCnt = values.length;
double expectedAvg = expectedSum / Math.max(1, expectedCnt);
- Assert.assertEquals(expectedAvg, metric.getAvg(), (double)200);
- Assert.assertEquals(expectedMin, metric.getMin());
- Assert.assertEquals(expectedMax, metric.getMax());
- Assert.assertEquals(expectedCnt, metric.getCount());
- Assert.assertEquals(expectedSum, metric.getTotal());
+ assertEquals(expectedAvg, metric.getAvg(), 200);
+ assertEquals(expectedMin, metric.getMin());
+ assertEquals(expectedMax, metric.getMax());
+ assertEquals(expectedCnt, metric.getCount());
+ assertEquals(expectedSum, metric.getTotal());
final Map<String, Object> results = metric.values();
- Assert.assertEquals(expectedMax, (long)results.get("max_test"));
- Assert.assertEquals(expectedMin, (long)results.get("min_test"));
- Assert.assertEquals(expectedCnt, (long)results.get("cnt_test"));
- Assert.assertEquals(expectedAvg, (double)results.get("avg_test"), (double)200);
+ assertEquals(expectedMax, (long) results.get("max_test"));
+ assertEquals(expectedMin, (long) results.get("min_test"));
+ assertEquals(expectedCnt, (long) results.get("cnt_test"));
+ assertEquals(expectedAvg, (double) results.get("avg_test"), 200);
metric.reset();
}
@@ -99,11 +99,12 @@ public class ServerMetricsTest extends ZKTestCase {
}
long expectedCount = Arrays.stream(values).sum();
- Assert.assertEquals(expectedCount, metric.get());
+ assertEquals(expectedCount, metric.get());
final Map<String, Object> results = metric.values();
- Assert.assertEquals(expectedCount, (long)results.get("test"));
+ assertEquals(expectedCount, (long) results.get("test"));
metric.reset();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
index 357b73e18..05a35058e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,14 +18,14 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.mockito.Mockito.mock;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import org.apache.zookeeper.ZKTestCase;
+import org.junit.Before;
+import org.junit.Test;
public class ServerStatsTest extends ZKTestCase {
@@ -50,8 +50,8 @@ public class ServerStatsTest extends ZKTestCase {
}
// Then ...
- Assert.assertEquals(incrementCount, serverStats.getPacketsSent());
- Assert.assertEquals(incrementCount*2, serverStats.getPacketsReceived());
+ assertEquals(incrementCount, serverStats.getPacketsSent());
+ assertEquals(incrementCount * 2, serverStats.getPacketsReceived());
// When reset ...
serverStats.resetRequestCounters();
@@ -72,11 +72,9 @@ public class ServerStatsTest extends ZKTestCase {
serverStats.updateLatency(fakeRequest, fakeRequest.createTime + 2000);
// Then ...
- assertThat("Max latency check", 2000L,
- lessThanOrEqualTo(serverStats.getMaxLatency()));
- assertThat("Min latency check", 1000L,
- lessThanOrEqualTo(serverStats.getMinLatency()));
- Assert.assertEquals((double)1500, serverStats.getAvgLatency(), (double)200);
+ assertThat("Max latency check", 2000L, lessThanOrEqualTo(serverStats.getMaxLatency()));
+ assertThat("Min latency check", 1000L, lessThanOrEqualTo(serverStats.getMinLatency()));
+ assertEquals(1500, serverStats.getAvgLatency(), 200);
// When reset...
serverStats.resetLatency();
@@ -97,7 +95,7 @@ public class ServerStatsTest extends ZKTestCase {
}
// Then ...
- Assert.assertEquals(incrementCount, serverStats.getFsyncThresholdExceedCount());
+ assertEquals(incrementCount, serverStats.getFsyncThresholdExceedCount());
// When reset ...
serverStats.resetFsyncThresholdExceedCount();
@@ -129,17 +127,18 @@ public class ServerStatsTest extends ZKTestCase {
}
private void assertAllPacketsZero(ServerStats serverStats) {
- Assert.assertEquals(0L, serverStats.getPacketsSent());
- Assert.assertEquals(0L, serverStats.getPacketsReceived());
+ assertEquals(0L, serverStats.getPacketsSent());
+ assertEquals(0L, serverStats.getPacketsReceived());
}
private void assertAllLatencyZero(ServerStats serverStats) {
- Assert.assertEquals(0L, serverStats.getMaxLatency());
- Assert.assertEquals(0L, serverStats.getMinLatency());
- Assert.assertEquals((double)0, serverStats.getAvgLatency(), (double)0.00001);
+ assertEquals(0L, serverStats.getMaxLatency());
+ assertEquals(0L, serverStats.getMinLatency());
+ assertEquals(0, serverStats.getAvgLatency(), 0.00001);
}
private void assertFsyncThresholdExceedCountZero(ServerStats serverStats) {
- Assert.assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
+ assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
index c2e0b1200..c00855077 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,21 +18,22 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.server.SessionTrackerImpl.SessionImpl;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* Testing zk client session logic in sessiontracker
@@ -56,10 +57,8 @@ public class SessionTrackerTest extends ZKTestCase {
latch = new CountDownLatch(1);
zks.sessionTracker.trackSession(sessionId, sessionTimeout);
SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
- SessionImpl sessionImpl = sessionTrackerImpl.sessionsById
- .get(sessionId);
- Assert.assertNotNull("Sessionid:" + sessionId
- + " doesn't exists in sessiontracker", sessionImpl);
+ SessionImpl sessionImpl = sessionTrackerImpl.sessionsById.get(sessionId);
+ assertNotNull("Sessionid:" + sessionId + " doesn't exists in sessiontracker", sessionImpl);
// verify the session existence
Object sessionOwner = new Object();
@@ -74,17 +73,13 @@ public class SessionTrackerTest extends ZKTestCase {
sessionTrackerImpl.trackSession(sessionId, sessionTimeout);
try {
sessionTrackerImpl.checkSession(sessionId, sessionOwner);
- Assert.fail("Should throw session expiry exception "
- + "as the session has expired and closed");
+ fail("Should throw session expiry exception " + "as the session has expired and closed");
} catch (KeeperException.SessionExpiredException e) {
// expected behaviour
}
- Assert.assertTrue("Session didn't expired", sessionImpl.isClosing());
- Assert.assertFalse("Session didn't expired", sessionTrackerImpl
- .touchSession(sessionId, sessionTimeout));
- Assert.assertEquals(
- "Duplicate session expiry request has been generated", 1,
- firstProcessor.getCountOfCloseSessionReq());
+ assertTrue("Session didn't expired", sessionImpl.isClosing());
+ assertFalse("Session didn't expired", sessionTrackerImpl.touchSession(sessionId, sessionTimeout));
+ assertEquals("Duplicate session expiry request has been generated", 1, firstProcessor.getCountOfCloseSessionReq());
}
/**
@@ -98,10 +93,8 @@ public class SessionTrackerTest extends ZKTestCase {
latch = new CountDownLatch(1);
zks.sessionTracker.trackSession(sessionId, sessionTimeout);
SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
- SessionImpl sessionImpl = sessionTrackerImpl.sessionsById
- .get(sessionId);
- Assert.assertNotNull("Sessionid:" + sessionId
- + " doesn't exists in sessiontracker", sessionImpl);
+ SessionImpl sessionImpl = sessionTrackerImpl.sessionsById.get(sessionId);
+ assertNotNull("Sessionid:" + sessionId + " doesn't exists in sessiontracker", sessionImpl);
// verify the session existence
Object sessionOwner = new Object();
@@ -113,10 +106,8 @@ public class SessionTrackerTest extends ZKTestCase {
// Simulating close session request: removeSession() will be executed
// while OpCode.closeSession
sessionTrackerImpl.removeSession(sessionId);
- SessionImpl actualSession = sessionTrackerImpl.sessionsById
- .get(sessionId);
- Assert.assertNull("Session:" + sessionId
- + " still exists after removal", actualSession);
+ SessionImpl actualSession = sessionTrackerImpl.sessionsById.get(sessionId);
+ assertNull("Session:" + sessionId + " still exists after removal", actualSession);
}
private ZooKeeperServer setupSessionTracker() throws IOException {
@@ -136,10 +127,10 @@ public class SessionTrackerTest extends ZKTestCase {
// Mock processor used in zookeeper server
private class FirstProcessor extends PrepRequestProcessor {
+
private volatile int countOfCloseSessionReq = 0;
- public FirstProcessor(ZooKeeperServer zks,
- RequestProcessor nextProcessor) {
+ public FirstProcessor(ZooKeeperServer zks, RequestProcessor nextProcessor) {
super(zks, nextProcessor);
}
@@ -156,5 +147,7 @@ public class SessionTrackerTest extends ZKTestCase {
int getCountOfCloseSessionReq() {
return countOfCloseSessionReq;
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
index f74eb03f1..b3459a159 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,12 +18,13 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.ZooDefs;
@@ -34,21 +35,16 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeerMainTest;
import org.apache.zookeeper.server.util.DigestCalculator;
import org.apache.zookeeper.test.ClientBase;
-
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-
import org.mockito.Mockito;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SnapshotDigestTest extends ClientBase {
- private static final Logger LOG = LoggerFactory.getLogger(
- SnapshotDigestTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SnapshotDigestTest.class);
private ZooKeeper zk;
private ZooKeeperServer server;
@@ -89,15 +85,14 @@ public class SnapshotDigestTest extends ClientBase {
public void testSnapshotDigest() throws Exception {
// take a empty snapshot without creating any txn and make sure
// there is no digest mismatch issue
- server.takeSnapshot();
+ server.takeSnapshot();
reloadSnapshotAndCheckDigest();
-
+
// trigger various write requests
String pathPrefix = "/testSnapshotDigest";
for (int i = 0; i < 1000; i++) {
String path = pathPrefix + i;
- zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
// update the data of first node
@@ -111,25 +106,24 @@ public class SnapshotDigestTest extends ClientBase {
List<Op> subTxns = new ArrayList<Op>();
for (int i = 0; i < 3; i++) {
String path = pathPrefix + "-m" + i;
- subTxns.add(Op.create(path, path.getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
+ subTxns.add(Op.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
}
zk.multi(subTxns);
reloadSnapshotAndCheckDigest();
- // Take a snapshot and test the logic when loading a non-fuzzy snapshot
+ // Take a snapshot and test the logic when loading a non-fuzzy snapshot
server = serverFactory.getZooKeeperServer();
- server.takeSnapshot();
+ server.takeSnapshot();
reloadSnapshotAndCheckDigest();
}
/**
- * Make sure the code will skip digest check when it's comparing
- * digest with different version.
+ * Make sure the code will skip digest check when it's comparing
+ * digest with different version.
*
- * This enables us to smoonthly add new fields into digest or using
+ * This enables us to smoonthly add new fields into digest or using
* new digest calculation.
*/
@Test
@@ -139,11 +133,10 @@ public class SnapshotDigestTest extends ClientBase {
// create a node
String path = "/testDifferentDigestVersion";
- zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// take a full snapshot
- server.takeSnapshot();
+ server.takeSnapshot();
// using reflection to change the final static DIGEST_VERSION
int newVersion = currentVersion + 1;
@@ -154,23 +147,21 @@ public class SnapshotDigestTest extends ClientBase {
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newVersion);
- Assert.assertEquals(newVersion, (int) DigestCalculator.DIGEST_VERSION);
+ assertEquals(newVersion, (int) DigestCalculator.DIGEST_VERSION);
- // using mock to return different digest value when the way we
+ // using mock to return different digest value when the way we
// calculate digest changed
FileTxnSnapLog txnSnapLog = new FileTxnSnapLog(tmpDir, tmpDir);
DataTree dataTree = Mockito.spy(new DataTree());
- Mockito.when(dataTree.getTreeDigest()).thenReturn(0L);
- txnSnapLog.restore(dataTree, new ConcurrentHashMap<Long, Integer>(),
- Mockito.mock(FileTxnSnapLog.PlayBackListener.class));
+ Mockito.when(dataTree.getTreeDigest()).thenReturn(0L);
+ txnSnapLog.restore(dataTree, new ConcurrentHashMap<Long, Integer>(), Mockito.mock(FileTxnSnapLog.PlayBackListener.class));
// make sure the reportDigestMismatch function is never called
- Mockito.verify(dataTree, Mockito.never())
- .reportDigestMismatch(Mockito.anyLong());
+ Mockito.verify(dataTree, Mockito.never()).reportDigestMismatch(Mockito.anyLong());
}
/**
- * Make sure it's backward compatible, and also we can rollback this
+ * Make sure it's backward compatible, and also we can rollback this
* feature without corrupt the database.
*/
@Test
@@ -187,20 +178,19 @@ public class SnapshotDigestTest extends ClientBase {
// restart the server to cache the option change
reloadSnapshotAndCheckDigest();
-
- // create a node
+
+ // create a node
String path = "/testCompatible" + "-" + enabledBefore + "-" + enabledAfter;
- zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// take a full snapshot
- server.takeSnapshot();
+ server.takeSnapshot();
DigestCalculator.setDigestEnabled(enabledAfter);
-
+
reloadSnapshotAndCheckDigest();
- Assert.assertEquals(path, new String(zk.getData(path, false, null)));
+ assertEquals(path, new String(zk.getData(path, false, null)));
}
private void reloadSnapshotAndCheckDigest() throws Exception {
@@ -213,10 +203,10 @@ public class SnapshotDigestTest extends ClientBase {
QuorumPeerMainTest.waitForOne(zk, States.CONNECTED);
// Snapshot digests always match
- Assert.assertEquals(0L, (long) ServerMetrics.getMetrics().DIGEST_MISMATCHES_COUNT.get());
+ assertEquals(0L, ServerMetrics.getMetrics().DIGEST_MISMATCHES_COUNT.get());
// reset the digestFromLoadedSnapshot after comparing
- Assert.assertNull(server.getZKDatabase().getDataTree()
- .getDigestFromLoadedSnapshot());
+ assertNull(server.getZKDatabase().getDataTree().getDigestFromLoadedSnapshot());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
index f19469b17..e1349a3cd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,9 +18,9 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertNotSame;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.proto.SetDataRequest;
-import org.junit.Assert;
import org.junit.Test;
/**
@@ -28,11 +28,13 @@ import org.junit.Test;
* fail.
*/
public class ToStringTest extends ZKTestCase {
- /** Verify jute - which we've had particular problems with in the past
+
+ /** Verify jute - which we've had particular problems with in the past
* wrt null fields */
@Test
public void testJuteToString() {
SetDataRequest req = new SetDataRequest(null, null, 0);
- Assert.assertNotSame("ERROR", req.toString());
+ assertNotSame("ERROR", req.toString());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
index ce90936d3..243e17782 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,20 +18,21 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooDefs;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.metrics.MetricsUtils;
+import org.junit.Test;
public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
+
CountDownLatch processed;
private class MyRequestProcessor implements RequestProcessor {
+
@Override
public void processRequest(Request request) throws RequestProcessorException {
// use this dummy request processor to trigger a unrecoverable ex
@@ -41,9 +42,11 @@ public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
@Override
public void shutdown() {
}
+
}
private class MyPrepRequestProcessor extends PrepRequestProcessor {
+
public MyPrepRequestProcessor() {
super(new ZooKeeperServer(), new MyRequestProcessor());
}
@@ -57,21 +60,20 @@ public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
}
@Test
- public void testUnrecoverableErrorCountFromRequestProcessor() throws Exception{
+ public void testUnrecoverableErrorCountFromRequestProcessor() throws Exception {
ServerMetrics.getMetrics().resetAll();
processed = new CountDownLatch(1);
- PrepRequestProcessor processor =new MyPrepRequestProcessor();
+ PrepRequestProcessor processor = new MyPrepRequestProcessor();
processor.start();
- processor.processRequest(new Request(null, 1L, 1, ZooDefs.OpCode.setData,
- ByteBuffer.wrap(new byte[10]), null));
+ processor.processRequest(new Request(null, 1L, 1, ZooDefs.OpCode.setData, ByteBuffer.wrap(new byte[10]), null));
processed.await();
processor.shutdown();
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("unrecoverable_error_count"));
+ assertEquals(1L, values.get("unrecoverable_error_count"));
}
@Test
@@ -84,6 +86,7 @@ public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
thread.handleException("test", new Exception());
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("unrecoverable_error_count"));
+ assertEquals(1L, values.get("unrecoverable_error_count"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
index d268410d8..a8db9e286 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,16 +15,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
-
import org.apache.jute.Record;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
@@ -36,10 +35,10 @@ import org.junit.Before;
import org.junit.Test;
public class ZooKeeperServerBeanTest {
+
@Before
public void setup() {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
}
@After
@@ -51,8 +50,7 @@ public class ZooKeeperServerBeanTest {
public void testTxnLogElapsedSyncTime() throws IOException {
File tmpDir = ClientBase.createEmptyTestDir();
- FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"),
- new File(tmpDir, "data_txnlog"));
+ FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
ZooKeeperServer zks = new ZooKeeperServer();
zks.setTxnLogFactory(fileTxnSnapLog);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
index 6fc257901..2f1c9e3bc 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
@@ -14,20 +14,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class ZooKeeperServerConfTest extends ZKTestCase {
+
private ZooKeeperServerConf c;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
c = new ZooKeeperServerConf(1, "a", "b", 2, 3, 4, 5, 6L, 7);
}
- @Test public void testGetters() {
+ @Test
+ public void testGetters() {
assertEquals(1, c.getClientPort());
assertEquals("a", c.getDataDir());
assertEquals("b", c.getDataLogDir());
@@ -38,7 +42,8 @@ public class ZooKeeperServerConfTest extends ZKTestCase {
assertEquals(6L, c.getServerId());
assertEquals(7, c.getClientPortListenBacklog());
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
Map<String, Object> m = c.toMap();
assertEquals(9, m.size());
assertEquals(Integer.valueOf(1), m.get(ZooKeeperServerConf.KEY_CLIENT_PORT));
@@ -51,4 +56,5 @@ public class ZooKeeperServerConfTest extends ZKTestCase {
assertEquals(Long.valueOf(6L), m.get(ZooKeeperServerConf.KEY_SERVER_ID));
assertEquals(Integer.valueOf(7), m.get(ZooKeeperServerConf.KEY_CLIENT_PORT_LISTEN_BACKLOG));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
index 2d7038324..b7df9323f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,25 +19,25 @@
package org.apache.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.PathUtils;
import org.apache.zookeeper.metrics.BaseTestMetricsProvider;
import org.apache.zookeeper.metrics.BaseTestMetricsProvider.MetricsProviderCapturingLifecycle;
@@ -48,33 +48,33 @@ import org.apache.zookeeper.metrics.BaseTestMetricsProvider.MetricsProviderWithE
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Test stand-alone server.
*
*/
public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
- protected static final Logger LOG =
- LoggerFactory.getLogger(ZooKeeperServerMainTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(ZooKeeperServerMainTest.class);
private CountDownLatch clientConnected = new CountDownLatch(1);
public static class MainThread extends Thread {
+
final File confFile;
final TestZKSMain main;
final File tmpDir;
final File dataDir;
final File logDir;
- public MainThread(int clientPort, boolean preCreateDirs, String configs)
- throws IOException {
+ public MainThread(int clientPort, boolean preCreateDirs, String configs) throws IOException {
this(clientPort, preCreateDirs, ClientBase.createTmpDir(), configs);
}
- public MainThread(int clientPort, boolean preCreateDirs, File tmpDir, String configs)
- throws IOException {
+ public MainThread(int clientPort, boolean preCreateDirs, File tmpDir, String configs) throws IOException {
super("Standalone server with clientPort:" + clientPort);
this.tmpDir = tmpDir;
confFile = new File(tmpDir, "zoo.cfg");
@@ -83,7 +83,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
fwriter.write("tickTime=2000\n");
fwriter.write("initLimit=10\n");
fwriter.write("syncLimit=5\n");
- if(configs != null){
+ if (configs != null) {
fwriter.write(configs);
}
@@ -98,7 +98,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
}
ClientBase.createInitializeFile(logDir);
}
-
+
String normalizedDataDir = PathUtils.normalizeFileSystemPath(dataDir.toString());
String normalizedLogDir = PathUtils.normalizeFileSystemPath(logDir.toString());
fwriter.write("dataDir=" + normalizedDataDir + "\n");
@@ -111,7 +111,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
}
public void run() {
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
@@ -125,31 +125,36 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main.shutdown();
}
- void deleteDirs() throws IOException{
+ void deleteDirs() throws IOException {
delete(tmpDir);
}
void delete(File f) throws IOException {
if (f.isDirectory()) {
- for (File c : f.listFiles())
+ for (File c : f.listFiles()) {
delete(c);
+ }
}
- if (!f.delete())
+ if (!f.delete()) {
// double check for the file existence
if (f.exists()) {
throw new IOException("Failed to delete file: " + f);
}
+ }
}
ServerCnxnFactory getCnxnFactory() {
return main.getCnxnFactory();
}
+
}
- public static class TestZKSMain extends ZooKeeperServerMain {
+ public static class TestZKSMain extends ZooKeeperServerMain {
+
public void shutdown() {
super.shutdown();
}
+
}
/**
@@ -166,24 +171,19 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
-
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
- zk.create("/foo1", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo1", null, null)), "foobar");
+ zk.create("/foo1", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo1", null, null)), "foobar");
// inject problem in server
- ZooKeeperServer zooKeeperServer = main.getCnxnFactory()
- .getZooKeeperServer();
+ ZooKeeperServer zooKeeperServer = main.getCnxnFactory().getZooKeeperServer();
FileTxnSnapLog snapLog = zooKeeperServer.getTxnLogFactory();
- FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(
- snapLog.getDataDir(), snapLog.getSnapDir()) {
+ FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(snapLog.getDataDir(), snapLog.getSnapDir()) {
@Override
public void commit() throws IOException {
throw new IOException("Input/output error");
@@ -194,16 +194,15 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
try {
// do create operation, so that injected IOException is thrown
- zk.create("/foo2", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo2", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
fail("IOException is expected as error is injected in transaction log commit funtionality");
} catch (Exception e) {
// do nothing
}
zk.close();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
fileTxnSnapLogWithError.close();
main.shutdown();
main.deleteDirs();
@@ -225,9 +224,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
File tmpDir = main.tmpDir;
main.start();
- Assert.assertTrue("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
// Make the snapshot directory read only
@@ -238,9 +237,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main = new MainThread(CLIENT_PORT, false, tmpDir, null);
main.start();
- Assert.assertFalse("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertFalse(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
@@ -265,9 +264,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
File tmpDir = main.tmpDir;
main.start();
- Assert.assertTrue("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
// Make the transaction log directory read only
@@ -278,9 +277,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main = new MainThread(CLIENT_PORT, false, tmpDir, null);
main.start();
- Assert.assertFalse("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertFalse(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
@@ -301,28 +300,25 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -330,23 +326,25 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* maxsessiontimeout
*/
@Test
- public void testWithMinSessionTimeoutGreaterThanMaxSessionTimeout()
- throws Exception {
+ public void testWithMinSessionTimeoutGreaterThanMaxSessionTimeout() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
final int tickTime = 2000;
final int minSessionTimeout = 20 * tickTime + 1000; // min is higher
final int maxSessionTimeout = tickTime * 2 - 100; // max is lower
- final String configs = "maxSessionTimeout=" + maxSessionTimeout + "\n"
- + "minSessionTimeout=" + minSessionTimeout + "\n";
+ final String configs = "maxSessionTimeout="
+ + maxSessionTimeout
+ + "\n"
+ + "minSessionTimeout="
+ + minSessionTimeout
+ + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as "
- + "minsessiontimeout > maxsessiontimeout");
+ fail("Must throw exception as " + "minsessiontimeout > maxsessiontimeout");
} catch (ConfigException iae) {
// expected
}
@@ -356,19 +354,17 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't boot with an invalid metrics provider
*/
@Test
- public void testInvalidMetricsProvider()
- throws Exception {
+ public void testInvalidMetricsProvider() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
final String configs = "metricsProvider.className=BadClass\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as metrics provider is not "
- + "well configured");
+ fail("Must throw exception as metrics provider is not " + "well configured");
} catch (ConfigException iae) {
// expected
}
@@ -378,18 +374,17 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't boot with a faulty metrics provider
*/
@Test
- public void testFaultyMetricsProviderOnStart()
- throws Exception {
+ public void testFaultyMetricsProviderOnStart() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- final String configs = "metricsProvider.className="+MetricsProviderWithErrorInStart.class.getName()+"\n";
+ final String configs = "metricsProvider.className=" + MetricsProviderWithErrorInStart.class.getName() + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as metrics provider cannot boot");
+ fail("Must throw exception as metrics provider cannot boot");
} catch (IOException iae) {
// expected
}
@@ -399,18 +394,19 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't boot with a faulty metrics provider
*/
@Test
- public void testFaultyMetricsProviderOnConfigure()
- throws Exception {
+ public void testFaultyMetricsProviderOnConfigure() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- final String configs = "metricsProvider.className="+MetricsProviderWithErrorInConfigure.class.getName()+"\n";
+ final String configs = "metricsProvider.className="
+ + MetricsProviderWithErrorInConfigure.class.getName()
+ + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as metrics provider is cannot boot");
+ fail("Must throw exception as metrics provider is cannot boot");
} catch (IOException iae) {
// expected
}
@@ -420,127 +416,112 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't be affected but runtime errors on stop()
*/
@Test
- public void testFaultyMetricsProviderOnStop()
- throws Exception {
+ public void testFaultyMetricsProviderOnStop() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MetricsProviderWithErrorInStop.stopCalled.set(false);
- final String configs = "metricsProvider.className="+MetricsProviderWithErrorInStop.class.getName()+"\n";
+ final String configs = "metricsProvider.className=" + MetricsProviderWithErrorInStop.class.getName() + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue(MetricsProviderWithErrorInStop.stopCalled.get());
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(MetricsProviderWithErrorInStop.stopCalled.get());
}
/**
* Test verifies that configuration is passed to the MetricsProvider.
*/
@Test
- public void testMetricsProviderConfiguration()
- throws Exception {
+ public void testMetricsProviderConfiguration() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MetricsProviderWithConfiguration.httpPort.set(0);
- final String configs = "metricsProvider.className="+MetricsProviderWithConfiguration.class.getName()+"\n"+
- "metricsProvider.httpPort=1234\n";
+ final String configs = "metricsProvider.className="
+ + MetricsProviderWithConfiguration.class.getName()
+ + "\n"
+ + "metricsProvider.httpPort=1234\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertEquals(1234, MetricsProviderWithConfiguration.httpPort.get());
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+ assertEquals(1234, MetricsProviderWithConfiguration.httpPort.get());
}
/**
* Test verifies that all of the lifecycle methods of the MetricsProvider are called.
*/
@Test
- public void testMetricsProviderLifecycle()
- throws Exception {
+ public void testMetricsProviderLifecycle() throws Exception {
ClientBase.setupTestEnv();
MetricsProviderCapturingLifecycle.reset();
final int CLIENT_PORT = PortAssignment.unique();
- final String configs = "metricsProvider.className="+MetricsProviderCapturingLifecycle.class.getName()+"\n"+
- "metricsProvider.httpPort=1234\n";
+ final String configs = "metricsProvider.className="
+ + MetricsProviderCapturingLifecycle.class.getName()
+ + "\n"
+ + "metricsProvider.httpPort=1234\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
-
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
+ assertTrue("waiting for server down", ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
}
/**
@@ -560,19 +541,15 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main.start();
String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
// create session with min value
verifySessionTimeOut(minSessionTimeout, minSessionTimeout, HOSTPORT);
- verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout, HOSTPORT);
// create session with max value
verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
- verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout, HOSTPORT);
main.shutdown();
- Assert.assertTrue("waiting for server down", ClientBase
- .waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -587,37 +564,33 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
final int tickTime = 2000;
final int minSessionTimeout = tickTime * 2 - 100;
final int maxSessionTimeout = 20 * tickTime + 1000;
- final String configs = "maxSessionTimeout=" + maxSessionTimeout + "\n"
- + "minSessionTimeout=" + minSessionTimeout + "\n";
+ final String configs = "maxSessionTimeout="
+ + maxSessionTimeout
+ + "\n"
+ + "minSessionTimeout="
+ + minSessionTimeout
+ + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
// create session with min value
verifySessionTimeOut(minSessionTimeout, minSessionTimeout, HOSTPORT);
- verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout, HOSTPORT);
// create session with max value
verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
- verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout, HOSTPORT);
main.shutdown();
- Assert.assertTrue("waiting for server down", ClientBase
- .waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
- private void verifySessionTimeOut(int sessionTimeout,
- int expectedSessionTimeout, String HOSTPORT) throws IOException,
- KeeperException, InterruptedException {
+ private void verifySessionTimeOut(int sessionTimeout, int expectedSessionTimeout, String HOSTPORT) throws IOException, KeeperException, InterruptedException {
clientConnected = new CountDownLatch(1);
ZooKeeper zk = new ZooKeeper(HOSTPORT, sessionTimeout, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(sessionTimeout, TimeUnit.MILLISECONDS));
- Assert.assertEquals("Not able to configure the sessionTimeout values",
- expectedSessionTimeout, zk.getSessionTimeout());
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(sessionTimeout, TimeUnit.MILLISECONDS));
+ assertEquals("Not able to configure the sessionTimeout values", expectedSessionTimeout, zk.getSessionTimeout());
zk.close();
}
@@ -638,10 +611,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
@Test
public void testJMXRegistrationWithNetty() throws Exception {
- String originalServerCnxnFactory = System
- .getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- NettyServerCnxnFactory.class.getName());
+ String originalServerCnxnFactory = System.getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
try {
ClientBase.setupTestEnv();
File tmpDir_1 = ClientBase.createTmpDir();
@@ -656,39 +627,38 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
deleteFile(tmpDir_2);
} finally {
// setting back
- if (originalServerCnxnFactory == null
- || originalServerCnxnFactory.isEmpty()) {
+ if (originalServerCnxnFactory == null || originalServerCnxnFactory.isEmpty()) {
System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
} else {
- System.setProperty(
- ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- originalServerCnxnFactory);
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, originalServerCnxnFactory);
}
}
}
private void deleteFile(File f) throws IOException {
if (f.isDirectory()) {
- for (File c : f.listFiles())
+ for (File c : f.listFiles()) {
deleteFile(c);
+ }
}
- if (!f.delete())
- // double check for the file existence
+ if (!f.delete()) {
+ // double check for the file existence
+
if (f.exists()) {
throw new IOException("Failed to delete file: " + f);
}
+ }
}
- private ServerCnxnFactory startServer(File tmpDir) throws IOException,
- InterruptedException {
+ private ServerCnxnFactory startServer(File tmpDir) throws IOException, InterruptedException {
final int CLIENT_PORT = PortAssignment.unique();
ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(CLIENT_PORT, -1);
f.startup(zks);
- Assert.assertNotNull("JMX initialization failed!", zks.jmxServerBean);
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertNotNull("JMX initialization failed!", zks.jmxServerBean);
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
return f;
}
@@ -697,4 +667,5 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
clientConnected.countDown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
index bdf763e81..794d6dcf8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,16 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
import static org.apache.zookeeper.server.command.AbstractFourLetterCommand.ZK_NOT_SERVING;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooKeeper;
@@ -32,7 +34,6 @@ import org.apache.zookeeper.common.X509Exception.SSLContextException;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,8 +42,8 @@ import org.slf4j.LoggerFactory;
* This class tests the startup behavior of ZooKeeper server.
*/
public class ZooKeeperServerStartupTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory
- .getLogger(ZooKeeperServerStartupTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperServerStartupTest.class);
private static int PORT = PortAssignment.unique();
private static String HOST = "127.0.0.1";
private static String HOSTPORT = HOST + ":" + PORT;
@@ -75,35 +76,25 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
* https://issues.apache.org/jira/browse/ZOOKEEPER-2383
*/
@Test(timeout = 30000)
- public void testClientConnectionRequestDuringStartupWithNIOServerCnxn()
- throws Exception {
+ public void testClientConnectionRequestDuringStartupWithNIOServerCnxn() throws Exception {
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
startSimpleZKServer(startupDelayLatch);
SimpleZooKeeperServer simplezks = (SimpleZooKeeperServer) zks;
- Assert.assertTrue(
- "Failed to invoke zks#startup() method during server startup",
- simplezks.waitForStartupInvocation(10));
+ assertTrue("Failed to invoke zks#startup() method during server startup", simplezks.waitForStartupInvocation(10));
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zkClient = new ZooKeeper(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ ZooKeeper zkClient = new ZooKeeper(HOSTPORT, ClientBase.CONNECTION_TIMEOUT, watcher);
- Assert.assertFalse(
- "Since server is not fully started, zks#createSession() shouldn't be invoked",
- simplezks.waitForSessionCreation(5));
+ assertFalse("Since server is not fully started, zks#createSession() shouldn't be invoked", simplezks.waitForSessionCreation(5));
- LOG.info(
- "Decrements the count of the latch, so that server will proceed with startup");
+ LOG.info("Decrements the count of the latch, so that server will proceed with startup");
startupDelayLatch.countDown();
- Assert.assertTrue("waiting for server being up ", ClientBase
- .waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue(
- "Failed to invoke zks#createSession() method during client session creation",
- simplezks.waitForSessionCreation(5));
+ assertTrue("Failed to invoke zks#createSession() method during client session creation", simplezks.waitForSessionCreation(5));
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
zkClient.close();
}
@@ -113,51 +104,37 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
* https://issues.apache.org/jira/browse/ZOOKEEPER-2383
*/
@Test(timeout = 30000)
- public void testClientConnectionRequestDuringStartupWithNettyServerCnxn()
- throws Exception {
+ public void testClientConnectionRequestDuringStartupWithNettyServerCnxn() throws Exception {
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
- String originalServerCnxnFactory = System
- .getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
+ String originalServerCnxnFactory = System.getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
try {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- NettyServerCnxnFactory.class.getName());
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
startSimpleZKServer(startupDelayLatch);
SimpleZooKeeperServer simplezks = (SimpleZooKeeperServer) zks;
- Assert.assertTrue(
- "Failed to invoke zks#startup() method during server startup",
- simplezks.waitForStartupInvocation(10));
+ assertTrue("Failed to invoke zks#startup() method during server startup", simplezks.waitForStartupInvocation(10));
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zkClient = new ZooKeeper(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ ZooKeeper zkClient = new ZooKeeper(HOSTPORT, ClientBase.CONNECTION_TIMEOUT, watcher);
- Assert.assertFalse(
- "Since server is not fully started, zks#createSession() shouldn't be invoked",
- simplezks.waitForSessionCreation(5));
+ assertFalse("Since server is not fully started, zks#createSession() shouldn't be invoked", simplezks.waitForSessionCreation(5));
- LOG.info(
- "Decrements the count of the latch, so that server will proceed with startup");
+ LOG.info("Decrements the count of the latch, so that server will proceed with startup");
startupDelayLatch.countDown();
- Assert.assertTrue("waiting for server being up ", ClientBase
- .waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue(
- "Failed to invoke zks#createSession() method during client session creation",
- simplezks.waitForSessionCreation(5));
+ assertTrue("Failed to invoke zks#createSession() method during client session creation", simplezks.waitForSessionCreation(5));
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
zkClient.close();
} finally {
// reset cnxn factory
if (originalServerCnxnFactory == null) {
- System.clearProperty(
- ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
+ System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
return;
}
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- originalServerCnxnFactory);
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, originalServerCnxnFactory);
}
}
@@ -182,22 +159,18 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
verify("isro", "null");
}
- private void verify(String cmd, String expected)
- throws IOException, SSLContextException {
+ private void verify(String cmd, String expected) throws IOException, SSLContextException {
String resp = sendRequest(cmd);
LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
- Assert.assertTrue("Unexpected response", resp.contains(expected));
+ assertTrue("Unexpected response", resp.contains(expected));
}
- private String sendRequest(String cmd)
- throws IOException, SSLContextException {
+ private String sendRequest(String cmd) throws IOException, SSLContextException {
return send4LetterWord(HOST, PORT, cmd);
}
- private void startSimpleZKServer(CountDownLatch startupDelayLatch)
- throws IOException {
- zks = new SimpleZooKeeperServer(tmpDir, tmpDir, 3000,
- startupDelayLatch);
+ private void startSimpleZKServer(CountDownLatch startupDelayLatch) throws IOException {
+ zks = new SimpleZooKeeperServer(tmpDir, tmpDir, 3000, startupDelayLatch);
SyncRequestProcessor.setSnapCount(100);
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
@@ -215,20 +188,19 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
// Ignoring exception. If there is an interrupted exception
// then one of the following assertion will fail
}
- };
+ }
};
LOG.info("Starting zk server {}", HOSTPORT);
startupThread.start();
}
private static class SimpleZooKeeperServer extends ZooKeeperServer {
+
private CountDownLatch startupDelayLatch;
private CountDownLatch startupInvokedLatch = new CountDownLatch(1);
- private CountDownLatch createSessionInvokedLatch = new CountDownLatch(
- 1);
+ private CountDownLatch createSessionInvokedLatch = new CountDownLatch(1);
- public SimpleZooKeeperServer(File snapDir, File logDir, int tickTime,
- CountDownLatch startupDelayLatch) throws IOException {
+ public SimpleZooKeeperServer(File snapDir, File logDir, int tickTime, CountDownLatch startupDelayLatch) throws IOException {
super(snapDir, logDir, tickTime);
this.startupDelayLatch = startupDelayLatch;
}
@@ -245,8 +217,7 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
// the startup phase, resulting in NPE.
startupDelayLatch.await();
} catch (InterruptedException e) {
- Assert.fail(
- "Unexpected InterruptedException while startinng up!");
+ fail("Unexpected InterruptedException while startinng up!");
}
super.startup();
}
@@ -257,14 +228,14 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
return super.createSession(cnxn, passwd, timeout);
}
- boolean waitForStartupInvocation(long timeout)
- throws InterruptedException {
+ boolean waitForStartupInvocation(long timeout) throws InterruptedException {
return startupInvokedLatch.await(timeout, TimeUnit.SECONDS);
}
- boolean waitForSessionCreation(long timeout)
- throws InterruptedException {
+ boolean waitForSessionCreation(long timeout) throws InterruptedException {
return createSessionInvokedLatch.await(timeout, TimeUnit.SECONDS);
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
index 3ba3872b1..81469a8f8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,19 +18,21 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.List;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.persistence.FileTxnLog;
import org.apache.zookeeper.server.persistence.SnapStream;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
public class ZooKeeperServerTest extends ZKTestCase {
+
@Test
public void testSortDataDirAscending() {
File[] files = new File[5];
@@ -45,11 +47,11 @@ public class ZooKeeperServerTest extends ZKTestCase {
List<File> filelist = Util.sortDataDir(files, "foo", true);
- Assert.assertEquals(orig[2], filelist.get(0));
- Assert.assertEquals(orig[3], filelist.get(1));
- Assert.assertEquals(orig[0], filelist.get(2));
- Assert.assertEquals(orig[1], filelist.get(3));
- Assert.assertEquals(orig[4], filelist.get(4));
+ assertEquals(orig[2], filelist.get(0));
+ assertEquals(orig[3], filelist.get(1));
+ assertEquals(orig[0], filelist.get(2));
+ assertEquals(orig[1], filelist.get(3));
+ assertEquals(orig[4], filelist.get(4));
}
@Test
@@ -66,11 +68,11 @@ public class ZooKeeperServerTest extends ZKTestCase {
List<File> filelist = Util.sortDataDir(files, "foo", false);
- Assert.assertEquals(orig[4], filelist.get(0));
- Assert.assertEquals(orig[1], filelist.get(1));
- Assert.assertEquals(orig[0], filelist.get(2));
- Assert.assertEquals(orig[3], filelist.get(3));
- Assert.assertEquals(orig[2], filelist.get(4));
+ assertEquals(orig[4], filelist.get(0));
+ assertEquals(orig[1], filelist.get(1));
+ assertEquals(orig[0], filelist.get(2));
+ assertEquals(orig[3], filelist.get(3));
+ assertEquals(orig[2], filelist.get(4));
}
@Test
@@ -85,34 +87,31 @@ public class ZooKeeperServerTest extends ZKTestCase {
File[] orig = files.clone();
- File[] filelist =
- FileTxnLog.getLogFiles(files,
- Long.parseLong("10027c6de", 16));
+ File[] filelist = FileTxnLog.getLogFiles(files, Long.parseLong("10027c6de", 16));
- Assert.assertEquals(3, filelist.length);
- Assert.assertEquals(orig[0], filelist[0]);
- Assert.assertEquals(orig[1], filelist[1]);
- Assert.assertEquals(orig[4], filelist[2]);
+ assertEquals(3, filelist.length);
+ assertEquals(orig[0], filelist[0]);
+ assertEquals(orig[1], filelist[1]);
+ assertEquals(orig[4], filelist[2]);
}
@Test
public void testForceSyncDefaultEnabled() {
File file = new File("foo.10027c6de");
FileTxnLog log = new FileTxnLog(file);
- Assert.assertTrue(log.isForceSync());
+ assertTrue(log.isForceSync());
}
@Test
public void testForceSyncDefaultDisabled() {
try {
File file = new File("foo.10027c6de");
- System.setProperty("zookeeper.forceSync","no");
+ System.setProperty("zookeeper.forceSync", "no");
FileTxnLog log = new FileTxnLog(file);
- Assert.assertFalse(log.isForceSync());
- }
- finally {
+ assertFalse(log.isForceSync());
+ } finally {
//Reset back to default.
- System.setProperty("zookeeper.forceSync","yes");
+ System.setProperty("zookeeper.forceSync", "yes");
}
}
@@ -126,8 +125,8 @@ public class ZooKeeperServerTest extends ZKTestCase {
if (!f.exists()) {
f.createNewFile();
}
- Assert.assertFalse("Snapshot file size is greater than 9 bytes", SnapStream.isValidSnapshot(f));
- Assert.assertTrue("Can't delete file", f.delete());
+ assertFalse("Snapshot file size is greater than 9 bytes", SnapStream.isValidSnapshot(f));
+ assertTrue("Can't delete file", f.delete());
} catch (IOException e) {
} finally {
if (null != tmpFileDir) {
@@ -135,4 +134,5 @@ public class ZooKeeperServerTest extends ZKTestCase {
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
index 2c737fc55..fe53f4d12 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,17 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
public class ZooKeeperThreadTest extends ZKTestCase {
+
private CountDownLatch runningLatch = new CountDownLatch(1);
public class MyThread extends ZooKeeperThread {
@@ -42,6 +42,7 @@ public class ZooKeeperThreadTest extends ZKTestCase {
protected void handleException(String thName, Throwable e) {
runningLatch.countDown();
}
+
}
public class MyCriticalThread extends ZooKeeperCriticalThread {
@@ -64,6 +65,7 @@ public class ZooKeeperThreadTest extends ZKTestCase {
protected void handleException(String thName, Throwable e) {
runningLatch.countDown();
}
+
}
/**
@@ -73,13 +75,12 @@ public class ZooKeeperThreadTest extends ZKTestCase {
public void testUncaughtException() throws Exception {
MyThread t1 = new MyThread("Test-Thread");
t1.start();
- Assert.assertTrue("Uncaught exception is not properly handled.",
- runningLatch.await(10000, TimeUnit.MILLISECONDS));
+ assertTrue("Uncaught exception is not properly handled.", runningLatch.await(10000, TimeUnit.MILLISECONDS));
runningLatch = new CountDownLatch(1);
MyCriticalThread t2 = new MyCriticalThread("Test-Critical-Thread");
t2.start();
- Assert.assertTrue("Uncaught exception is not properly handled.",
- runningLatch.await(10000, TimeUnit.MILLISECONDS));
+ assertTrue("Uncaught exception is not properly handled.", runningLatch.await(10000, TimeUnit.MILLISECONDS));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
index 838b0a809..42e366ec5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,7 +18,10 @@
package org.apache.zookeeper.server;
-
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
@@ -31,7 +34,6 @@ import org.apache.zookeeper.test.ClientTest;
import org.apache.zookeeper.test.QuorumUtil;
import org.apache.zookeeper.test.QuorumUtil.PeerStruct;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -41,6 +43,7 @@ import org.slf4j.LoggerFactory;
* Verify ZOOKEEPER-1277 - ensure that we handle epoch rollover correctly.
*/
public class ZxidRolloverTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(ZxidRolloverTest.class);
private QuorumUtil qu;
@@ -49,9 +52,9 @@ public class ZxidRolloverTest extends ZKTestCase {
private CountdownWatcher[] zkClientWatchers = new CountdownWatcher[3];
private int idxLeader;
private int idxFollower;
-
+
private ZooKeeper getClient(int idx) {
- return zkClients[idx-1];
+ return zkClients[idx - 1];
}
@Before
@@ -70,11 +73,12 @@ public class ZxidRolloverTest extends ZKTestCase {
PeerStruct peer = qu.getPeer(i + 1);
zkClients[i] = new ZooKeeper(
"127.0.0.1:" + peer.clientPort,
- ClientTest.CONNECTION_TIMEOUT, zkClientWatchers[i]);
+ ClientTest.CONNECTION_TIMEOUT,
+ zkClientWatchers[i]);
}
waitForClientsConnected();
}
-
+
private void waitForClientsConnected() throws Exception {
for (int i = 0; i < zkClients.length; i++) {
zkClientWatchers[i].waitForConnected(ClientTest.CONNECTION_TIMEOUT);
@@ -93,7 +97,7 @@ public class ZxidRolloverTest extends ZKTestCase {
/**
* Ensure the client is able to talk to the server.
- *
+ *
* @param idx the idx of the server the client is talking to
*/
private void checkClientConnected(int idx) throws Exception {
@@ -102,7 +106,7 @@ public class ZxidRolloverTest extends ZKTestCase {
return;
}
try {
- Assert.assertNull(zk.exists("/foofoofoo-connected", false));
+ assertNull(zk.exists("/foofoofoo-connected", false));
} catch (ConnectionLossException e) {
// second chance...
// in some cases, leader change in particular, the timing is
@@ -113,10 +117,11 @@ public class ZxidRolloverTest extends ZKTestCase {
// in the try, this catches that case and waits for the server
// to come back
PeerStruct peer = qu.getPeer(idx);
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerUp(
- "127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerUp("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertNull(zk.exists("/foofoofoo-connected", false));
+ assertNull(zk.exists("/foofoofoo-connected", false));
}
}
@@ -131,7 +136,7 @@ public class ZxidRolloverTest extends ZKTestCase {
/**
* Ensure the client is able to talk to the server
- *
+ *
* @param idx the idx of the server the client is talking to
*/
private void checkClientDisconnected(int idx) throws Exception {
@@ -140,8 +145,8 @@ public class ZxidRolloverTest extends ZKTestCase {
return;
}
try {
- Assert.assertNull(zk.exists("/foofoofoo-disconnected", false));
- Assert.fail("expected client to be disconnected");
+ assertNull(zk.exists("/foofoofoo-disconnected", false));
+ fail("expected client to be disconnected");
} catch (KeeperException e) {
// success
}
@@ -156,8 +161,7 @@ public class ZxidRolloverTest extends ZKTestCase {
private void start(int idx) throws Exception {
qu.start(idx);
for (String hp : qu.getConnString().split(",")) {
- Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(hp,
- ClientTest.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, ClientTest.CONNECTION_TIMEOUT));
}
checkLeader();
@@ -167,7 +171,7 @@ public class ZxidRolloverTest extends ZKTestCase {
private void checkLeader() {
idxLeader = 1;
- while(qu.getPeer(idxLeader).peer.leader == null) {
+ while (qu.getPeer(idxLeader).peer.leader == null) {
idxLeader++;
}
idxFollower = (idxLeader == 1 ? 2 : 1);
@@ -180,14 +184,15 @@ public class ZxidRolloverTest extends ZKTestCase {
// all clients should be disconnected
checkClientsDisconnected();
}
-
+
private void shutdown(int idx) throws Exception {
qu.shutdown(idx);
// leader will shutdown, remaining followers will elect a new leader
PeerStruct peer = qu.getPeer(idx);
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerDown(
- "127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
// if idx is the the leader then everyone will get disconnected,
// otherwise if idx is a follower then just that client will get
@@ -228,8 +233,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int j = 0;
try {
for (int i = start; i < start + count; i++) {
- zk.create("/foo" + i, new byte[0], Ids.READ_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create("/foo" + i, new byte[0], Ids.READ_ACL_UNSAFE, CreateMode.EPHEMERAL);
j++;
}
} catch (ConnectionLossException e) {
@@ -245,10 +249,10 @@ public class ZxidRolloverTest extends ZKTestCase {
private void checkNodes(ZooKeeper zk, int start, int count) throws Exception {
LOG.info("Validating nodes {} thru {}", start, (start + count));
for (int i = start; i < start + count; i++) {
- Assert.assertNotNull(zk.exists("/foo" + i, false));
+ assertNotNull(zk.exists("/foo" + i, false));
LOG.error("Exists zxid:{}", Long.toHexString(zk.exists("/foo" + i, false).getCzxid()));
}
- Assert.assertNull(zk.exists("/foo" + (start + count), false));
+ assertNull(zk.exists("/foo" + (start + count), false));
}
/**
@@ -261,7 +265,7 @@ public class ZxidRolloverTest extends ZKTestCase {
ZooKeeper zk = getClient((idxLeader == 1 ? 2 : 1));
int countCreated = createNodes(zk, 0, 10);
-
+
checkNodes(zk, 0, countCreated);
}
@@ -272,11 +276,11 @@ public class ZxidRolloverTest extends ZKTestCase {
@Test
public void testRolloverThenRestart() throws Exception {
ZooKeeper zk = getClient(idxFollower);
-
+
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
shutdownAll();
@@ -287,7 +291,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
countCreated += createNodes(zk, countCreated, 10);
@@ -306,8 +310,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 60);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 60);
}
/**
@@ -321,7 +325,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
shutdown(idxFollower);
@@ -331,7 +335,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
countCreated += createNodes(zk, countCreated, 10);
@@ -348,8 +352,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 60);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 60);
}
/**
@@ -363,7 +367,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
shutdown(idxLeader);
@@ -374,7 +378,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
countCreated += createNodes(zk, countCreated, 10);
@@ -393,8 +397,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 50);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 50);
}
/**
@@ -408,7 +412,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
@@ -416,7 +420,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
@@ -440,7 +444,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 70);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 70);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
index ab8c25860..20dc40792 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
@@ -17,26 +17,30 @@
package org.apache.zookeeper.server.admin;
+import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
public class CommandResponseTest extends ZKTestCase {
+
private CommandResponse r;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
r = new CommandResponse("makemeasandwich", "makeityourself");
}
- @Test public void testGetters() {
+ @Test
+ public void testGetters() {
assertEquals("makemeasandwich", r.getCommand());
assertEquals("makeityourself", r.getError());
}
- @Test public void testMap() {
+ @Test
+ public void testMap() {
r.put("missing", "sudo");
Map<String, Object> m = new HashMap<String, Object>();
m.put("origin", "xkcd");
@@ -51,4 +55,5 @@ public class CommandResponseTest extends ZKTestCase {
assertEquals("xkcd", rmap.get("origin"));
assertEquals("http://xkcd.com/149/", rmap.get("url"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
index 86b5207ee..6afbbe2e0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -25,16 +25,13 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.zookeeper.metrics.MetricsUtils;
-
import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.server.ServerStats;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.quorum.BufferStats;
@@ -42,6 +39,7 @@ import org.apache.zookeeper.test.ClientBase;
import org.junit.Test;
public class CommandsTest extends ClientBase {
+
/**
* Checks that running a given Command returns the expected Map. Asserts
* that all specified keys are present with values of the specified types
@@ -56,8 +54,7 @@ public class CommandsTest extends ClientBase {
* @throws IOException
* @throws InterruptedException
*/
- public void testCommand(String cmdName, Map<String, String> kwargs, Field... fields)
- throws IOException, InterruptedException {
+ public void testCommand(String cmdName, Map<String, String> kwargs, Field... fields) throws IOException, InterruptedException {
ZooKeeperServer zks = serverFactory.getZooKeeperServer();
Map<String, Object> result = Commands.runCommand(cmdName, zks, kwargs).toMap();
@@ -69,61 +66,56 @@ public class CommandsTest extends ClientBase {
for (Field field : fields) {
String k = field.key;
- assertTrue("Result from command " + cmdName + " missing field \"" + k + "\""
- + "\n" + result,
- result.containsKey(k));
+ assertTrue("Result from command "
+ + cmdName
+ + " missing field \""
+ + k
+ + "\""
+ + "\n"
+ + result, result.containsKey(k));
Class<?> t = field.type;
Object v = result.remove(k);
- assertTrue("\"" + k + "\" field from command " + cmdName + " should be of type " + t
- + ", is actually of type " + v.getClass(),
- t.isAssignableFrom(v.getClass()));
+ assertTrue("\""
+ + k
+ + "\" field from command "
+ + cmdName
+ + " should be of type "
+ + t
+ + ", is actually of type "
+ + v.getClass(), t.isAssignableFrom(v.getClass()));
}
- assertTrue("Result from command " + cmdName + " contains extra fields: " + result,
- result.isEmpty());
+ assertTrue("Result from command " + cmdName + " contains extra fields: " + result, result.isEmpty());
}
- public void testCommand(String cmdName, Field... fields)
- throws IOException, InterruptedException {
+ public void testCommand(String cmdName, Field... fields) throws IOException, InterruptedException {
testCommand(cmdName, new HashMap<String, String>(), fields);
}
private static class Field {
+
String key;
Class<?> type;
Field(String key, Class<?> type) {
this.key = key;
this.type = type;
}
+
}
@Test
public void testConfiguration() throws IOException, InterruptedException {
- testCommand("configuration",
- new Field("client_port", Integer.class),
- new Field("data_dir", String.class),
- new Field("data_log_dir", String.class),
- new Field("tick_time", Integer.class),
- new Field("max_client_cnxns", Integer.class),
- new Field("min_session_timeout", Integer.class),
- new Field("max_session_timeout", Integer.class),
- new Field("server_id", Long.class),
- new Field("client_port_listen_backlog", Integer.class));
+ testCommand("configuration", new Field("client_port", Integer.class), new Field("data_dir", String.class), new Field("data_log_dir", String.class), new Field("tick_time", Integer.class), new Field("max_client_cnxns", Integer.class), new Field("min_session_timeout", Integer.class), new Field("max_session_timeout", Integer.class), new Field("server_id", Long.class), new Field("client_port_listen_backlog", Integer.class));
}
@Test
public void testConnections() throws IOException, InterruptedException {
- testCommand("connections",
- new Field("connections", Iterable.class),
- new Field("secure_connections", Iterable.class)
- );
+ testCommand("connections", new Field("connections", Iterable.class), new Field("secure_connections", Iterable.class));
}
@Test
public void testObservers() throws IOException, InterruptedException {
- testCommand("observers",
- new Field("synced_observers", Integer.class),
- new Field("observers", Iterable.class));
+ testCommand("observers", new Field("synced_observers", Integer.class), new Field("observers", Iterable.class));
}
@Test
@@ -138,98 +130,49 @@ public class CommandsTest extends ClientBase {
@Test
public void testDump() throws IOException, InterruptedException {
- testCommand("dump",
- new Field("expiry_time_to_session_ids", Map.class),
- new Field("session_id_to_ephemeral_paths", Map.class));
+ testCommand("dump", new Field("expiry_time_to_session_ids", Map.class), new Field("session_id_to_ephemeral_paths", Map.class));
}
@Test
public void testEnvironment() throws IOException, InterruptedException {
- testCommand("environment",
- new Field("zookeeper.version", String.class),
- new Field("host.name", String.class),
- new Field("java.version", String.class),
- new Field("java.vendor", String.class),
- new Field("java.home", String.class),
- new Field("java.class.path", String.class),
- new Field("java.library.path", String.class),
- new Field("java.io.tmpdir", String.class),
- new Field("java.compiler", String.class),
- new Field("os.name", String.class),
- new Field("os.arch", String.class),
- new Field("os.version", String.class),
- new Field("user.name", String.class),
- new Field("user.home", String.class),
- new Field("user.dir", String.class),
- new Field("os.memory.free", String.class),
- new Field("os.memory.max", String.class),
- new Field("os.memory.total", String.class));
+ testCommand("environment", new Field("zookeeper.version", String.class), new Field("host.name", String.class), new Field("java.version", String.class), new Field("java.vendor", String.class), new Field("java.home", String.class), new Field("java.class.path", String.class), new Field("java.library.path", String.class), new Field("java.io.tmpdir", String.class), new Field("java.compiler", String.class), new Field("os.name", String.class), new Field("os.arch", String.class), new Field("os.version", String.class), new Field("user.name", String.class), new Field("user.home", String.class), new Field("user.dir", String.class), new Field("os.memory.free", String.class), new Field("os.memory.max", String.class), new Field("os.memory.total", String.class));
}
@Test
public void testGetTraceMask() throws IOException, InterruptedException {
- testCommand("get_trace_mask",
- new Field("tracemask", Long.class));
+ testCommand("get_trace_mask", new Field("tracemask", Long.class));
}
@Test
public void testIsReadOnly() throws IOException, InterruptedException {
- testCommand("is_read_only",
- new Field("read_only", Boolean.class));
+ testCommand("is_read_only", new Field("read_only", Boolean.class));
}
@Test
public void testLastSnapshot() throws IOException, InterruptedException {
- testCommand("last_snapshot",
- new Field("zxid", String.class),
- new Field("timestamp", Long.class));
+ testCommand("last_snapshot", new Field("zxid", String.class), new Field("timestamp", Long.class));
}
@Test
public void testMonitor() throws IOException, InterruptedException {
- ArrayList<Field> fields = new ArrayList<>(Arrays.asList(
- new Field("version", String.class),
- new Field("avg_latency", Double.class),
- new Field("max_latency", Long.class),
- new Field("min_latency", Long.class),
- new Field("packets_received", Long.class),
- new Field("packets_sent", Long.class),
- new Field("num_alive_connections", Integer.class),
- new Field("outstanding_requests", Long.class),
- new Field("server_state", String.class),
- new Field("znode_count", Integer.class),
- new Field("watch_count", Integer.class),
- new Field("ephemerals_count", Integer.class),
- new Field("approximate_data_size", Long.class),
- new Field("open_file_descriptor_count", Long.class),
- new Field("max_file_descriptor_count", Long.class),
- new Field("last_client_response_size", Integer.class),
- new Field("max_client_response_size", Integer.class),
- new Field("min_client_response_size", Integer.class),
- new Field("uptime", Long.class),
- new Field("global_sessions", Long.class),
- new Field("local_sessions", Long.class),
- new Field("connection_drop_probability", Double.class)
- ));
+ ArrayList<Field> fields = new ArrayList<>(Arrays.asList(new Field("version", String.class), new Field("avg_latency", Double.class), new Field("max_latency", Long.class), new Field("min_latency", Long.class), new Field("packets_received", Long.class), new Field("packets_sent", Long.class), new Field("num_alive_connections", Integer.class), new Field("outstanding_requests", Long.class), new Field("server_state", String.class), new Field("znode_count", Integer.class), new Field("watch_count", Integer.class), new Field("ephemerals_count", Integer.class), new Field("approximate_data_size", Long.class), new Field("open_file_descriptor_count", Long.class), new Field("max_file_descriptor_count", Long.class), new Field("last_client_response_size", Integer.class), new Field("max_client_response_size", Integer.class), new Field("min_client_response_size", Integer.class), new Field("uptime", Long.class), new Field("global_sessions", Long.class), new Field("local_sessions", Long.class), new Field("connection_drop_probability", Double.class)));
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
-
+
for (String metric : metrics.keySet()) {
- boolean alreadyDefined = fields
- .stream()
- .anyMatch(f -> {
- return f.key.equals(metric);
- });
+ boolean alreadyDefined = fields.stream().anyMatch(f -> {
+ return f.key.equals(metric);
+ });
if (alreadyDefined) {
// known metrics are defined statically in the block above
continue;
}
if (metric.startsWith("avg_")) {
- fields.add(new Field(metric, Double.class));
+ fields.add(new Field(metric, Double.class));
} else {
fields.add(new Field(metric, Long.class));
}
}
- Field fieldsArray[] = fields.toArray(new Field[0]);
+ Field[] fieldsArray = fields.toArray(new Field[0]);
testCommand("monitor", fieldsArray);
}
@@ -240,31 +183,19 @@ public class CommandsTest extends ClientBase {
@Test
public void testServerStats() throws IOException, InterruptedException {
- testCommand("server_stats",
- new Field("version", String.class),
- new Field("read_only", Boolean.class),
- new Field("server_stats", ServerStats.class),
- new Field("node_count", Integer.class),
- new Field("client_response", BufferStats.class));
+ testCommand("server_stats", new Field("version", String.class), new Field("read_only", Boolean.class), new Field("server_stats", ServerStats.class), new Field("node_count", Integer.class), new Field("client_response", BufferStats.class));
}
@Test
public void testSetTraceMask() throws IOException, InterruptedException {
Map<String, String> kwargs = new HashMap<String, String>();
kwargs.put("traceMask", "1");
- testCommand("set_trace_mask", kwargs,
- new Field("tracemask", Long.class));
+ testCommand("set_trace_mask", kwargs, new Field("tracemask", Long.class));
}
@Test
public void testStat() throws IOException, InterruptedException {
- testCommand("stats",
- new Field("version", String.class),
- new Field("read_only", Boolean.class),
- new Field("server_stats", ServerStats.class),
- new Field("node_count", Integer.class),
- new Field("connections", Iterable.class),
- new Field("client_response", BufferStats.class));
+ testCommand("stats", new Field("version", String.class), new Field("read_only", Boolean.class), new Field("server_stats", ServerStats.class), new Field("node_count", Integer.class), new Field("connections", Iterable.class), new Field("client_response", BufferStats.class));
}
@Test
@@ -274,22 +205,17 @@ public class CommandsTest extends ClientBase {
@Test
public void testWatches() throws IOException, InterruptedException {
- testCommand("watches",
- new Field("session_id_to_watched_paths", Map.class));
+ testCommand("watches", new Field("session_id_to_watched_paths", Map.class));
}
@Test
public void testWatchesByPath() throws IOException, InterruptedException {
- testCommand("watches_by_path",
- new Field("path_to_session_ids", Map.class));
+ testCommand("watches_by_path", new Field("path_to_session_ids", Map.class));
}
@Test
public void testWatchSummary() throws IOException, InterruptedException {
- testCommand("watch_summary",
- new Field("num_connections", Integer.class),
- new Field("num_paths", Integer.class),
- new Field("num_total_watches", Integer.class));
+ testCommand("watch_summary", new Field("num_connections", Integer.class), new Field("num_paths", Integer.class), new Field("num_total_watches", Integer.class));
}
@Test
@@ -307,4 +233,5 @@ public class CommandsTest extends ClientBase {
assertThat(response.toMap().containsKey("connections"), is(true));
assertThat(response.toMap().containsKey("secure_connections"), is(true));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
index 26ca2f9e3..71c244684 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,20 +18,25 @@
package org.apache.zookeeper.server.admin;
+import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.net.MalformedURLException;
import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.Security;
+import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
-
-import org.apache.zookeeper.common.KeyStoreFileType;
-import org.apache.zookeeper.common.X509Exception.SSLContextException;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.common.KeyStoreFileType;
+import org.apache.zookeeper.common.X509Exception.SSLContextException;
import org.apache.zookeeper.common.X509KeyType;
import org.apache.zookeeper.common.X509TestContext;
import org.apache.zookeeper.server.ZooKeeperServerMainTest;
@@ -40,20 +45,13 @@ import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.apache.zookeeper.test.ClientBase;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import java.security.Security;
-import java.security.cert.X509Certificate;
-import java.security.GeneralSecurityException;
+public class JettyAdminServerTest extends ZKTestCase {
-public class JettyAdminServerTest extends ZKTestCase{
protected static final Logger LOG = LoggerFactory.getLogger(JettyAdminServerTest.class);
private static final String URL_FORMAT = "http://localhost:%d/commands";
@@ -75,16 +73,18 @@ public class JettyAdminServerTest extends ZKTestCase{
try {
tmpDir = ClientBase.createEmptyTestDir();
x509TestContext = X509TestContext.newBuilder()
- .setTempDir(tmpDir)
- .setKeyStorePassword("")
- .setKeyStoreKeyType(X509KeyType.EC)
- .setTrustStorePassword("")
- .setTrustStoreKeyType(X509KeyType.EC)
- .build();
- System.setProperty("zookeeper.ssl.quorum.keyStore.location",
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
- System.setProperty("zookeeper.ssl.quorum.trustStore.location",
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
+ .setTempDir(tmpDir)
+ .setKeyStorePassword("")
+ .setKeyStoreKeyType(X509KeyType.EC)
+ .setTrustStorePassword("")
+ .setTrustStoreKeyType(X509KeyType.EC)
+ .build();
+ System.setProperty(
+ "zookeeper.ssl.quorum.keyStore.location",
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
+ System.setProperty(
+ "zookeeper.ssl.quorum.trustStore.location",
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
} catch (Exception e) {
LOG.info("Problems encountered while setting up encryption for Jetty admin server test: " + e);
}
@@ -95,10 +95,14 @@ public class JettyAdminServerTest extends ZKTestCase{
System.setProperty("zookeeper.admin.portUnification", "true");
// Create a trust manager that does not validate certificate chains
- TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
- public void checkClientTrusted(X509Certificate[] certs, String authType) {}
- public void checkServerTrusted(X509Certificate[] certs, String authType) {}
+ TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+ public void checkClientTrusted(X509Certificate[] certs, String authType) {
+ }
+ public void checkServerTrusted(X509Certificate[] certs, String authType) {
+ }
}};
// Create all-trusting trust manager
@@ -106,11 +110,15 @@ public class JettyAdminServerTest extends ZKTestCase{
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
- } catch (Exception e) { LOG.error("Failed to customize encryption for HTTPS: e"); }
+ } catch (Exception e) {
+ LOG.error("Failed to customize encryption for HTTPS: e");
+ }
// Create all-trusting hostname verifier
HostnameVerifier allValid = new HostnameVerifier() {
- public boolean verify(String hostname, SSLSession session) { return true; }
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
};
// This is a temporary fix while we do not yet have certificates set up to make
@@ -140,7 +148,7 @@ public class JettyAdminServerTest extends ZKTestCase{
*/
@Test
public void testJettyAdminServer() throws AdminServerException, IOException, SSLContextException, GeneralSecurityException {
- JettyAdminServer server = new JettyAdminServer();;
+ JettyAdminServer server = new JettyAdminServer();
try {
server.start();
queryAdminServer(jettyAdminPort);
@@ -161,17 +169,17 @@ public class JettyAdminServerTest extends ZKTestCase{
ZooKeeperServerMainTest.MainThread main = new ZooKeeperServerMainTest.MainThread(CLIENT_PORT, false, null);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
queryAdminServer(jettyAdminPort);
main.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -187,13 +195,15 @@ public class JettyAdminServerTest extends ZKTestCase{
final int ADMIN_SERVER_PORT1 = PortAssignment.unique();
final int ADMIN_SERVER_PORT2 = PortAssignment.unique();
- String quorumCfgSection = String.format
- ("server.1=127.0.0.1:%d:%d;%d\nserver.2=127.0.0.1:%d:%d;%d",
- PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP1,
- PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP2
- );
- QuorumPeerTestBase.MainThread q1 = new QuorumPeerTestBase.MainThread(
- 1, CLIENT_PORT_QP1, ADMIN_SERVER_PORT1, quorumCfgSection, null);
+ String quorumCfgSection = String.format(
+ "server.1=127.0.0.1:%d:%d;%d\nserver.2=127.0.0.1:%d:%d;%d",
+ PortAssignment.unique(),
+ PortAssignment.unique(),
+ CLIENT_PORT_QP1,
+ PortAssignment.unique(),
+ PortAssignment.unique(),
+ CLIENT_PORT_QP2);
+ QuorumPeerTestBase.MainThread q1 = new QuorumPeerTestBase.MainThread(1, CLIENT_PORT_QP1, ADMIN_SERVER_PORT1, quorumCfgSection, null);
q1.start();
// Since JettyAdminServer reads a system property to determine its port,
@@ -201,18 +211,17 @@ public class JettyAdminServerTest extends ZKTestCase{
// again with the second port number
Thread.sleep(500);
- QuorumPeerTestBase.MainThread q2 = new QuorumPeerTestBase.MainThread(
- 2, CLIENT_PORT_QP2, ADMIN_SERVER_PORT2, quorumCfgSection, null);
+ QuorumPeerTestBase.MainThread q2 = new QuorumPeerTestBase.MainThread(2, CLIENT_PORT_QP2, ADMIN_SERVER_PORT2, quorumCfgSection, null);
q2.start();
Thread.sleep(500);
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
queryAdminServer(ADMIN_SERVER_PORT1);
queryAdminServer(ADMIN_SERVER_PORT2);
@@ -220,19 +229,19 @@ public class JettyAdminServerTest extends ZKTestCase{
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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
}
/**
* Check that we can load the commands page of an AdminServer running at
* localhost:port. (Note that this should work even if no zk server is set.)
*/
- private void queryAdminServer(int port) throws MalformedURLException, IOException, SSLContextException {
+ private void queryAdminServer(int port) throws IOException, SSLContextException {
queryAdminServer(String.format(URL_FORMAT, port), false);
queryAdminServer(String.format(HTTPS_URL_FORMAT, port), true);
}
@@ -240,7 +249,7 @@ public class JettyAdminServerTest extends ZKTestCase{
/**
* Check that loading urlStr results in a non-zero length response.
*/
- private void queryAdminServer(String urlStr, boolean encrypted) throws MalformedURLException, IOException, SSLContextException {
+ private void queryAdminServer(String urlStr, boolean encrypted) throws IOException, SSLContextException {
URL url = new URL(urlStr);
BufferedReader dis;
if (!encrypted) {
@@ -250,6 +259,7 @@ public class JettyAdminServerTest extends ZKTestCase{
dis = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
String line = dis.readLine();
- Assert.assertTrue(line.length() > 0);
+ assertTrue(line.length() > 0);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
index 308698148..50e3788cc 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,16 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.metric;
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class AvgMinMaxCounterSetTest extends ZKTestCase {
+
private AvgMinMaxCounterSet testCounterSet;
@Before
@@ -48,19 +49,19 @@ public class AvgMinMaxCounterSetTest extends ZKTestCase {
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("There should be 10 values in the set", 10, values.size());
+ assertEquals("There should be 10 values in the set", 10, values.size());
- Assert.assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
+ assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
- Assert.assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
+ assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
}
@@ -69,17 +70,18 @@ public class AvgMinMaxCounterSetTest extends ZKTestCase {
addDataPoints();
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("There should be 10 values in the set", 10, values.size());
- Assert.assertEquals("avg_key1_test should =0.5", 0.5D, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =1", 1L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =2", 2L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =1", 1L, values.get("sum_key1_test"));
-
- Assert.assertEquals("avg_key2_test should =3.5", 3.5, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =2", 2L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =5", 5L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =4", 4L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =14", 14L, values.get("sum_key2_test"));
+ assertEquals("There should be 10 values in the set", 10, values.size());
+ assertEquals("avg_key1_test should =0.5", 0.5D, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =1", 1L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =2", 2L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =1", 1L, values.get("sum_key1_test"));
+
+ assertEquals("avg_key2_test should =3.5", 3.5, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =2", 2L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =5", 5L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =4", 4L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =14", 14L, values.get("sum_key2_test"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
index 43d289f4c..e120ac51a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,16 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.metric;
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
+
private AvgMinMaxPercentileCounterSet testCounterSet;
@Before
@@ -33,11 +34,11 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
}
private void addDataPoints() {
- for (int i=0; i<1000; i++) {
+ for (int i = 0; i < 1000; i++) {
testCounterSet.add("key1", i);
}
- for (int i=1000; i<2000; i++) {
+ for (int i = 1000; i < 2000; i++) {
testCounterSet.add("key2", i);
}
}
@@ -49,25 +50,25 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
- Assert.assertEquals("p50_key1_test should have p50=0", 0L, values.get("p50_key1_test"));
- Assert.assertEquals("p95_key1_test should have p95=0", 0L, values.get("p95_key1_test"));
- Assert.assertEquals("p99_key1_test should have p99=0", 0L, values.get("p99_key1_test"));
- Assert.assertEquals("p999_key1_test should have p999=0", 0L, values.get("p999_key1_test"));
-
- Assert.assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
- Assert.assertEquals("p50_key2_test should have p50=0", 0L, values.get("p50_key2_test"));
- Assert.assertEquals("p95_key2_test should have p95=0", 0L, values.get("p95_key2_test"));
- Assert.assertEquals("p99_key2_test should have p99=0", 0L, values.get("p99_key2_test"));
- Assert.assertEquals("p999_key2_test should have p999=0", 0L, values.get("p999_key2_test"));
+ assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
+ assertEquals("p50_key1_test should have p50=0", 0L, values.get("p50_key1_test"));
+ assertEquals("p95_key1_test should have p95=0", 0L, values.get("p95_key1_test"));
+ assertEquals("p99_key1_test should have p99=0", 0L, values.get("p99_key1_test"));
+ assertEquals("p999_key1_test should have p999=0", 0L, values.get("p999_key1_test"));
+
+ assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
+ assertEquals("p50_key2_test should have p50=0", 0L, values.get("p50_key2_test"));
+ assertEquals("p95_key2_test should have p95=0", 0L, values.get("p95_key2_test"));
+ assertEquals("p99_key2_test should have p99=0", 0L, values.get("p99_key2_test"));
+ assertEquals("p999_key2_test should have p999=0", 0L, values.get("p999_key2_test"));
}
@Test
@@ -75,26 +76,27 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
addDataPoints();
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("There should be 18 values in the set", 18, values.size());
-
- Assert.assertEquals("avg_key1_test should =499.5", 999D/2, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =999", 999L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =1000", 1000L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =999*500", 999*500L, values.get("sum_key1_test"));
- Assert.assertEquals("p50_key1_test should have p50=500", 500L, values.get("p50_key1_test"));
- Assert.assertEquals("p95_key1_test should have p95=950", 950L, values.get("p95_key1_test"));
- Assert.assertEquals("p99_key1_test should have p99=990", 990L, values.get("p99_key1_test"));
- Assert.assertEquals("p999_key1_test should have p999=999", 999L, values.get("p999_key1_test"));
-
- Assert.assertEquals("avg_key2_test should =3.5", 1000+999D/2, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =2", 1000L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =5", 1999L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =4", 1000L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =14", 2999*500L, values.get("sum_key2_test"));
- Assert.assertEquals("p50_key2_test should have p50=1500", 1500L, values.get("p50_key2_test"));
- Assert.assertEquals("p95_key2_test should have p95=1950", 1950L, values.get("p95_key2_test"));
- Assert.assertEquals("p99_key2_test should have p99=1990", 1990L, values.get("p99_key2_test"));
- Assert.assertEquals("p999_key2_test should have p999=1999", 1999L, values.get("p999_key2_test"));
+ assertEquals("There should be 18 values in the set", 18, values.size());
+
+ assertEquals("avg_key1_test should =499.5", 999D / 2, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =999", 999L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =1000", 1000L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =999*500", 999 * 500L, values.get("sum_key1_test"));
+ assertEquals("p50_key1_test should have p50=500", 500L, values.get("p50_key1_test"));
+ assertEquals("p95_key1_test should have p95=950", 950L, values.get("p95_key1_test"));
+ assertEquals("p99_key1_test should have p99=990", 990L, values.get("p99_key1_test"));
+ assertEquals("p999_key1_test should have p999=999", 999L, values.get("p999_key1_test"));
+
+ assertEquals("avg_key2_test should =3.5", 1000 + 999D / 2, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =2", 1000L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =5", 1999L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =4", 1000L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =14", 2999 * 500L, values.get("sum_key2_test"));
+ assertEquals("p50_key2_test should have p50=1500", 1500L, values.get("p50_key2_test"));
+ assertEquals("p95_key2_test should have p95=1950", 1950L, values.get("p95_key2_test"));
+ assertEquals("p99_key2_test should have p99=1990", 1990L, values.get("p99_key2_test"));
+ assertEquals("p999_key2_test should have p999=1999", 1999L, values.get("p999_key2_test"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
index f8b16e462..ecfdbbcfb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,15 +15,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.metric;
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
private AvgMinMaxPercentileCounter testCounter;
@@ -34,12 +34,11 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
}
private void addDataPoints() {
- for (int i=0; i<1000; i++) {
+ for (int i = 0; i < 1000; i++) {
testCounter.add(i);
}
}
-
@Test
public void testReset() {
addDataPoints();
@@ -47,17 +46,17 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
Map<String, Object> values = testCounter.values();
- Assert.assertEquals("There should be 9 values in the set", 9, values.size());
+ assertEquals("There should be 9 values in the set", 9, values.size());
- Assert.assertEquals("should avg=0", 0D, values.get("avg_test"));
- Assert.assertEquals("should have min=0", 0L, values.get("min_test"));
- Assert.assertEquals("should have max=0", 0L, values.get("max_test"));
- Assert.assertEquals("should have cnt=0", 0L, values.get("cnt_test"));
- Assert.assertEquals("should have sum=0", 0L, values.get("sum_test"));
- Assert.assertEquals("should have p50=0", 0L, values.get("p50_test"));
- Assert.assertEquals("should have p95=0", 0L, values.get("p95_test"));
- Assert.assertEquals("should have p99=0", 0L, values.get("p99_test"));
- Assert.assertEquals("should have p999=0", 0L, values.get("p999_test"));
+ assertEquals("should avg=0", 0D, values.get("avg_test"));
+ assertEquals("should have min=0", 0L, values.get("min_test"));
+ assertEquals("should have max=0", 0L, values.get("max_test"));
+ assertEquals("should have cnt=0", 0L, values.get("cnt_test"));
+ assertEquals("should have sum=0", 0L, values.get("sum_test"));
+ assertEquals("should have p50=0", 0L, values.get("p50_test"));
+ assertEquals("should have p95=0", 0L, values.get("p95_test"));
+ assertEquals("should have p99=0", 0L, values.get("p99_test"));
+ assertEquals("should have p999=0", 0L, values.get("p999_test"));
}
@Test
@@ -65,16 +64,17 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
addDataPoints();
Map<String, Object> values = testCounter.values();
- Assert.assertEquals("There should be 9 values in the set", 9, values.size());
+ assertEquals("There should be 9 values in the set", 9, values.size());
- Assert.assertEquals("should avg=499.5", 999D/2, values.get("avg_test"));
- Assert.assertEquals("should have min=0", 0L, values.get("min_test"));
- Assert.assertEquals("should have max=999", 999L, values.get("max_test"));
- Assert.assertEquals("should have cnt=1000", 1000L, values.get("cnt_test"));
- Assert.assertEquals("should have sum=999*500", 999*500L, values.get("sum_test"));
- Assert.assertEquals("should have p50=500", 500L, values.get("p50_test"));
- Assert.assertEquals("should have p95=950", 950L, values.get("p95_test"));
- Assert.assertEquals("should have p99=990", 990L, values.get("p99_test"));
- Assert.assertEquals("should have p999=999", 999L, values.get("p999_test"));
+ assertEquals("should avg=499.5", 999D / 2, values.get("avg_test"));
+ assertEquals("should have min=0", 0L, values.get("min_test"));
+ assertEquals("should have max=999", 999L, values.get("max_test"));
+ assertEquals("should have cnt=1000", 1000L, values.get("cnt_test"));
+ assertEquals("should have sum=999*500", 999 * 500L, values.get("sum_test"));
+ assertEquals("should have p50=500", 500L, values.get("p50_test"));
+ assertEquals("should have p95=950", 950L, values.get("p95_test"));
+ assertEquals("should have p99=990", 990L, values.get("p99_test"));
+ assertEquals("should have p999=999", 999L, values.get("p999_test"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
index 4aa8a7b46..7eb6f6003 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,13 +18,14 @@
package org.apache.zookeeper.server.persistence;
-import org.junit.Assert;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.zookeeper.server.DataTree;
import org.junit.Test;
@@ -40,45 +41,40 @@ public class EmptySnapshotTest {
super(snapDir);
}
- public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot,
- boolean fsync) throws IOException {
+ public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot, boolean fsync) throws IOException {
// Create empty new file.
- Assert.assertTrue(snapShot.createNewFile());
- throw new IOException("Created empty snapshot file from " +
- "MockFileSnap::serialize()");
+ assertTrue(snapShot.createNewFile());
+ throw new IOException("Created empty snapshot file from " + "MockFileSnap::serialize()");
}
}
@Test
public void testNoEmptySnapshot() throws Exception {
- File tmpFile = File.createTempFile("empty-snapshot-test", ".junit",
- new File(System.getProperty("build.test.dir", "build")));
+ File tmpFile = File.createTempFile("empty-snapshot-test", ".junit", new File(System.getProperty("build.test.dir", "build")));
File tmpDataDir = new File(tmpFile + ".dir");
- Assert.assertFalse(tmpDataDir.exists());
- Assert.assertTrue(tmpDataDir.mkdirs());
+ assertFalse(tmpDataDir.exists());
+ assertTrue(tmpDataDir.mkdirs());
FileTxnSnapLog snapLog = new FileTxnSnapLog(tmpDataDir, tmpDataDir);
snapLog.snapLog = new MockFileSnap(snapLog.dataDir);
- Assert.assertEquals(0,
- ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
+ assertEquals(0, ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
DataTree tree = new DataTree();
- tree.createNode("/empty-snapshot-test-1", "data".getBytes(), null, -1,
- -1, 1, 1);
+ tree.createNode("/empty-snapshot-test-1", "data".getBytes(), null, -1, -1, 1, 1);
try {
- snapLog.save(tree, new ConcurrentHashMap<Long, Integer>(), false);
- Assert.fail("Should have thrown an IOException");
+ snapLog.save(tree, new ConcurrentHashMap<>(), false);
+ fail("Should have thrown an IOException");
} catch (IOException e) {
+ // no op
}
- Assert.assertEquals(0,
- ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
+ assertEquals(0, ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
snapLog.snapLog = new FileSnap(snapLog.dataDir);
- snapLog.save(tree, new ConcurrentHashMap<Long, Integer>(), false);
- Assert.assertEquals(1,
- ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
- }
+ snapLog.save(tree, new ConcurrentHashMap<>(), false);
+ assertEquals(1, ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
+ }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
index e0d34abe2..4c17ac538 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,9 +15,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.persistence;
-import org.apache.zookeeper.*;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Random;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.proto.CreateRequest;
import org.apache.zookeeper.server.ServerCnxnFactory;
@@ -27,236 +44,239 @@ import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Random;
+public class FileTxnLogTest extends ZKTestCase {
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.mockito.Mockito.mock;
+ protected static final Logger LOG = LoggerFactory.getLogger(FileTxnLogTest.class);
+
+ private static final int KB = 1024;
+
+ @Test
+ public void testInvalidPreallocSize() {
+ assertEquals(
+ "file should not be padded",
+ 10 * KB,
+ FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 0));
+ assertEquals(
+ "file should not be padded",
+ 10 * KB,
+ FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, -1));
+ }
-public class FileTxnLogTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory.getLogger(FileTxnLogTest.class);
-
- private static final int KB = 1024;
-
- @Test
- public void testInvalidPreallocSize() {
- Assert.assertEquals("file should not be padded",
- 10 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 0));
- Assert.assertEquals("file should not be padded",
- 10 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, -1));
- }
-
- @Test
- public void testCalculateFileSizeWithPaddingWhenNotToCurrentSize() {
- Assert.assertEquals("file should not be padded",
- 10 * KB, FilePadding.calculateFileSizeWithPadding(5 * KB, 10 * KB, 10 * KB));
- }
-
- @Test
- public void testCalculateFileSizeWithPaddingWhenCloseToCurrentSize() {
- Assert.assertEquals("file should be padded an additional 10 KB",
- 20 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 10 * KB));
- }
-
- @Test
- public void testFileSizeGreaterThanPosition() {
- Assert.assertEquals("file should be padded to 40 KB",
- 40 * KB, FilePadding.calculateFileSizeWithPadding(31 * KB, 10 * KB, 10 * KB));
- }
-
- @Test
- public void testPreAllocSizeSmallerThanTxnData() throws IOException {
- File logDir = ClientBase.createTmpDir();
- FileTxnLog fileTxnLog = new FileTxnLog(logDir);
-
- // Set a small preAllocSize (.5 MB)
- final int preAllocSize = 500 * KB;
- FilePadding.setPreallocSize(preAllocSize);
-
- // Create dummy txn larger than preAllocSize
- // Since the file padding inserts a 0, we will fill the data with 0xff to ensure we corrupt the data if we put the 0 in the data
- byte[] data = new byte[2 * preAllocSize];
- Arrays.fill(data, (byte) 0xff);
-
- // Append and commit 2 transactions to the log
- // Prior to ZOOKEEPER-2249, attempting to pad in association with the second transaction will corrupt the first
- fileTxnLog.append(new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
- new CreateTxn("/testPreAllocSizeSmallerThanTxnData1", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
- fileTxnLog.commit();
- fileTxnLog.append(new TxnHeader(1, 1, 2, 2, ZooDefs.OpCode.create),
- new CreateTxn("/testPreAllocSizeSmallerThanTxnData2", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
- fileTxnLog.commit();
- fileTxnLog.close();
-
- // Read the log back from disk, this will throw a java.io.IOException: CRC check failed prior to ZOOKEEPER-2249
- FileTxnLog.FileTxnIterator fileTxnIterator = new FileTxnLog.FileTxnIterator(logDir, 0);
-
- // Verify the data in the first transaction
- CreateTxn createTxn = (CreateTxn) fileTxnIterator.getTxn();
- Assert.assertTrue(Arrays.equals(createTxn.getData(), data));
-
- // Verify the data in the second transaction
- fileTxnIterator.next();
- createTxn = (CreateTxn) fileTxnIterator.getTxn();
- Assert.assertTrue(Arrays.equals(createTxn.getData(), new byte[]{}));
- }
-
- @Test
- public void testSetPreallocSize() {
- long customPreallocSize = 10101;
- FileTxnLog.setPreallocSize(customPreallocSize);
- Assert.assertThat(FilePadding.getPreAllocSize(), is(equalTo(customPreallocSize)));
- }
-
- public void testSyncThresholdExceedCount() throws IOException {
- // Given ...
-
- // Set threshold to -1, as after the first commit it takes 0ms to commit to disk.
- java.lang.System.setProperty(FileTxnLog.ZOOKEEPER_FSYNC_WARNING_THRESHOLD_MS_PROPERTY, "-1");
- ServerStats.Provider providerMock = mock(ServerStats.Provider.class);
- ServerStats serverStats = new ServerStats(providerMock);
-
- File logDir = ClientBase.createTmpDir();
- FileTxnLog fileTxnLog = new FileTxnLog(logDir);
- fileTxnLog.setServerStats(serverStats);
-
- // Verify serverStats is 0 before any commit
- Assert.assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
-
- // When ...
- for (int i = 0; i < 50; i++) {
- fileTxnLog.append(new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
- new CreateTxn("/testFsyncThresholdCountIncreased", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
- fileTxnLog.commit(); // only 1 commit, otherwise it will be flaky
- // Then ... verify serverStats is updated to the number of commits (as threshold is set to 0)
- Assert.assertEquals((long) i + 1 , serverStats.getFsyncThresholdExceedCount());
+ @Test
+ public void testCalculateFileSizeWithPaddingWhenNotToCurrentSize() {
+ assertEquals(
+ "file should not be padded",
+ 10 * KB,
+ FilePadding.calculateFileSizeWithPadding(5 * KB, 10 * KB, 10 * KB));
}
- }
-
- private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private static final int CONNECTION_TIMEOUT = 3000;
-
- // Overhead is about 150 bytes for txn created in this test
- private static final int NODE_SIZE = 1024;
- private final long PREALLOCATE = 512;
- private final long LOG_SIZE_LIMIT = 1024 * 4;
-
- /**
- * Test that log size get update correctly
- */
- @Test
- public void testGetCurrentLogSize() throws Exception {
- FileTxnLog.setTxnLogSizeLimit(-1);
- File tmpDir = ClientBase.createTmpDir();
- FileTxnLog log = new FileTxnLog(tmpDir);
- FileTxnLog.setPreallocSize(PREALLOCATE);
- CreateRequest record = new CreateRequest(null, new byte[NODE_SIZE],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, 0);
- int zxid = 1;
- for (int i = 0; i < 4; i++) {
- log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
- LOG.debug("Current log size: " + log.getCurrentLogSize());
+
+ @Test
+ public void testCalculateFileSizeWithPaddingWhenCloseToCurrentSize() {
+ assertEquals(
+ "file should be padded an additional 10 KB",
+ 20 * KB,
+ FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 10 * KB));
}
- log.commit();
- LOG.info("Current log size: " + log.getCurrentLogSize());
- Assert.assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
- for (int i = 0; i < 4; i++) {
- log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
- LOG.debug("Current log size: " + log.getCurrentLogSize());
+
+ @Test
+ public void testFileSizeGreaterThanPosition() {
+ assertEquals(
+ "file should be padded to 40 KB",
+ 40 * KB,
+ FilePadding.calculateFileSizeWithPadding(31 * KB, 10 * KB, 10 * KB));
}
- log.commit();
- LOG.info("Current log size: " + log.getCurrentLogSize());
- Assert.assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
- }
-
- /**
- * Test that the server can correctly load the data when there are multiple
- * txnlogs per snapshot
- */
- @Test
- public void testLogSizeLimit() throws Exception {
- File tmpDir = ClientBase.createTmpDir();
- ClientBase.setupTestEnv();
-
- // Need to override preallocate set by setupTestEnv()
- // We don't need to unset these values since each unit test run in
- // a separate JVM instance
- FileTxnLog.setPreallocSize(PREALLOCATE);
- FileTxnLog.setTxnLogSizeLimit(LOG_SIZE_LIMIT);
-
- ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
- ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
- f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
- ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, event -> { });
-
- // Generate transactions
- HashSet<Long> zxids = new HashSet<Long>();
- byte[] bytes = new byte[NODE_SIZE];
- Random random = new Random();
- random.nextBytes(bytes);
-
- // We will create enough txn to generate 3 logs
- long txnCount = LOG_SIZE_LIMIT / NODE_SIZE / 2 * 5;
-
- LOG.info("Creating " + txnCount + " txns");
-
- try {
- for (long i = 0; i < txnCount; i++) {
- Stat stat = new Stat();
- zk.create("/node-" + i, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.getData("/node-" + i, null, stat);
- zxids.add(stat.getCzxid());
- }
-
- } finally {
- zk.close();
+
+ @Test
+ public void testPreAllocSizeSmallerThanTxnData() throws IOException {
+ File logDir = ClientBase.createTmpDir();
+ FileTxnLog fileTxnLog = new FileTxnLog(logDir);
+
+ // Set a small preAllocSize (.5 MB)
+ final int preAllocSize = 500 * KB;
+ FilePadding.setPreallocSize(preAllocSize);
+
+ // Create dummy txn larger than preAllocSize
+ // Since the file padding inserts a 0, we will fill the data with 0xff to ensure we corrupt the data if we put the 0 in the data
+ byte[] data = new byte[2 * preAllocSize];
+ Arrays.fill(data, (byte) 0xff);
+
+ // Append and commit 2 transactions to the log
+ // Prior to ZOOKEEPER-2249, attempting to pad in association with the second transaction will corrupt the first
+ fileTxnLog.append(
+ new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
+ new CreateTxn("/testPreAllocSizeSmallerThanTxnData1", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
+ fileTxnLog.commit();
+ fileTxnLog.append(
+ new TxnHeader(1, 1, 2, 2, ZooDefs.OpCode.create),
+ new CreateTxn("/testPreAllocSizeSmallerThanTxnData2", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
+ fileTxnLog.commit();
+ fileTxnLog.close();
+
+ // Read the log back from disk, this will throw a java.io.IOException: CRC check failed prior to ZOOKEEPER-2249
+ FileTxnLog.FileTxnIterator fileTxnIterator = new FileTxnLog.FileTxnIterator(logDir, 0);
+
+ // Verify the data in the first transaction
+ CreateTxn createTxn = (CreateTxn) fileTxnIterator.getTxn();
+ assertTrue(Arrays.equals(createTxn.getData(), data));
+
+ // Verify the data in the second transaction
+ fileTxnIterator.next();
+ createTxn = (CreateTxn) fileTxnIterator.getTxn();
+ assertTrue(Arrays.equals(createTxn.getData(), new byte[]{}));
}
- // shutdown
- f.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
+ @Test
+ public void testSetPreallocSize() {
+ long customPreallocSize = 10101;
+ FileTxnLog.setPreallocSize(customPreallocSize);
+ assertThat(FilePadding.getPreAllocSize(), is(equalTo(customPreallocSize)));
+ }
+
+ public void testSyncThresholdExceedCount() throws IOException {
+ // Given ...
+
+ // Set threshold to -1, as after the first commit it takes 0ms to commit to disk.
+ java.lang.System.setProperty(FileTxnLog.ZOOKEEPER_FSYNC_WARNING_THRESHOLD_MS_PROPERTY, "-1");
+ ServerStats.Provider providerMock = mock(ServerStats.Provider.class);
+ ServerStats serverStats = new ServerStats(providerMock);
+
+ File logDir = ClientBase.createTmpDir();
+ FileTxnLog fileTxnLog = new FileTxnLog(logDir);
+ fileTxnLog.setServerStats(serverStats);
+
+ // Verify serverStats is 0 before any commit
+ assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
+
+ // When ...
+ for (int i = 0; i < 50; i++) {
+ fileTxnLog.append(
+ new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
+ new CreateTxn("/testFsyncThresholdCountIncreased", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
+ fileTxnLog.commit(); // only 1 commit, otherwise it will be flaky
+ // Then ... verify serverStats is updated to the number of commits (as threshold is set to 0)
+ assertEquals((long) i + 1, serverStats.getFsyncThresholdExceedCount());
+ }
+ }
+
+ private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
+ private static final int CONNECTION_TIMEOUT = 3000;
+
+ // Overhead is about 150 bytes for txn created in this test
+ private static final int NODE_SIZE = 1024;
+ private final long PREALLOCATE = 512;
+ private final long LOG_SIZE_LIMIT = 1024 * 4;
+
+ /**
+ * Test that log size get update correctly
+ */
+ @Test
+ public void testGetCurrentLogSize() throws Exception {
+ FileTxnLog.setTxnLogSizeLimit(-1);
+ File tmpDir = ClientBase.createTmpDir();
+ FileTxnLog log = new FileTxnLog(tmpDir);
+ FileTxnLog.setPreallocSize(PREALLOCATE);
+ CreateRequest record = new CreateRequest(null, new byte[NODE_SIZE], ZooDefs.Ids.OPEN_ACL_UNSAFE, 0);
+ int zxid = 1;
+ for (int i = 0; i < 4; i++) {
+ log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
+ LOG.debug("Current log size: " + log.getCurrentLogSize());
+ }
+ log.commit();
+ LOG.info("Current log size: " + log.getCurrentLogSize());
+ assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
+ for (int i = 0; i < 4; i++) {
+ log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
+ LOG.debug("Current log size: " + log.getCurrentLogSize());
+ }
+ log.commit();
+ LOG.info("Current log size: " + log.getCurrentLogSize());
+ assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
+ }
+
+ /**
+ * Test that the server can correctly load the data when there are multiple
+ * txnlogs per snapshot
+ */
+ @Test
+ public void testLogSizeLimit() throws Exception {
+ File tmpDir = ClientBase.createTmpDir();
+ ClientBase.setupTestEnv();
+
+ // Need to override preallocate set by setupTestEnv()
+ // We don't need to unset these values since each unit test run in
+ // a separate JVM instance
+ FileTxnLog.setPreallocSize(PREALLOCATE);
+ FileTxnLog.setTxnLogSizeLimit(LOG_SIZE_LIMIT);
+
+ ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
+ final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
+ ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
+ f.startup(zks);
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, event -> {
+ });
+
+ // Generate transactions
+ HashSet<Long> zxids = new HashSet<Long>();
+ byte[] bytes = new byte[NODE_SIZE];
+ Random random = new Random();
+ random.nextBytes(bytes);
+
+ // We will create enough txn to generate 3 logs
+ long txnCount = LOG_SIZE_LIMIT / NODE_SIZE / 2 * 5;
+
+ LOG.info("Creating " + txnCount + " txns");
+
+ try {
+ for (long i = 0; i < txnCount; i++) {
+ Stat stat = new Stat();
+ zk.create("/node-" + i, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.getData("/node-" + i, null, stat);
+ zxids.add(stat.getCzxid());
+ }
+
+ } finally {
+ zk.close();
+ }
+
+ // shutdown
+ f.shutdown();
+ assertTrue(
+ "waiting for server to shutdown",
ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
- File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
- File[] txnLogs = FileTxnLog.getLogFiles(logDir.listFiles(), 0);
+ File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
+ File[] txnLogs = FileTxnLog.getLogFiles(logDir.listFiles(), 0);
- Assert.assertEquals("Unexpected number of logs", 3, txnLogs.length);
+ assertEquals("Unexpected number of logs", 3, txnLogs.length);
- // Log size should not exceed limit by more than one node size;
- long threshold = LOG_SIZE_LIMIT + NODE_SIZE;
- LOG.info(txnLogs[0].getAbsolutePath());
- Assert.assertTrue(
+ // Log size should not exceed limit by more than one node size;
+ long threshold = LOG_SIZE_LIMIT + NODE_SIZE;
+ LOG.info(txnLogs[0].getAbsolutePath());
+ assertTrue(
"Exceed log size limit: " + txnLogs[0].length(),
threshold > txnLogs[0].length());
- LOG.info(txnLogs[1].getAbsolutePath());
- Assert.assertTrue(
+ LOG.info(txnLogs[1].getAbsolutePath());
+ assertTrue(
"Exceed log size limit " + txnLogs[1].length(),
threshold > txnLogs[1].length());
- // Start database only
- zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- zks.startdata();
+ // Start database only
+ zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
+ zks.startdata();
- ZKDatabase db = zks.getZKDatabase();
+ ZKDatabase db = zks.getZKDatabase();
- for (long i = 0; i < txnCount; i++) {
- Stat stat = new Stat();
- byte[] data = db.getData("/node-" + i, stat, null);
- Assert.assertArrayEquals("Missmatch data", bytes, data);
- Assert.assertTrue("Unknown zxid ", zxids.contains(stat.getMzxid()));
+ for (long i = 0; i < txnCount; i++) {
+ Stat stat = new Stat();
+ byte[] data = db.getData("/node-" + i, stat, null);
+ assertArrayEquals("Missmatch data", bytes, data);
+ assertTrue("Unknown zxid ", zxids.contains(stat.getMzxid()));
+ }
}
- }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
index 4b4ef7a09..fe075fb49 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,39 +18,41 @@
package org.apache.zookeeper.server.persistence;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.WatchedEvent;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-
public class FileTxnSnapLogMetricsTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(FileTxnSnapLogMetricsTest.class);
CountDownLatch allCreatedLatch;
private class MockWatcher implements Watcher {
+
@Override
public void process(WatchedEvent e) {
LOG.info("all nodes created");
allCreatedLatch.countDown();
}
+
}
@Test
@@ -65,7 +67,7 @@ public class FileTxnSnapLogMetricsTest extends ZKTestCase {
byte[] data = new byte[500];
// make sure a snapshot is taken and some txns are not in a snapshot
ZooKeeper zk = ClientBase.createZKClient(util.getConnString());
- for (int i=0; i<150; i++){
+ for (int i = 0; i < 150; i++) {
zk.create("/path" + i, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@@ -81,13 +83,14 @@ public class FileTxnSnapLogMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
LOG.info("txn loaded during start up {}", values.get("max_startup_txns_loaded"));
- Assert.assertEquals(1L, values.get("cnt_startup_txns_loaded"));
- Assert.assertThat((long)values.get("max_startup_txns_loaded"), greaterThan(0L));
- Assert.assertEquals(1L, values.get("cnt_startup_txns_load_time"));
- Assert.assertThat((long)values.get("max_startup_txns_load_time"), greaterThanOrEqualTo(0L));
- Assert.assertEquals(1L, values.get("cnt_startup_snap_load_time"));
- Assert.assertThat((long)values.get("max_startup_snap_load_time"), greaterThan(0L));
+ assertEquals(1L, values.get("cnt_startup_txns_loaded"));
+ assertThat((long) values.get("max_startup_txns_loaded"), greaterThan(0L));
+ assertEquals(1L, values.get("cnt_startup_txns_load_time"));
+ assertThat((long) values.get("max_startup_txns_load_time"), greaterThanOrEqualTo(0L));
+ assertEquals(1L, values.get("cnt_startup_snap_load_time"));
+ assertThat((long) values.get("max_startup_snap_load_time"), greaterThan(0L));
util.shutdownAll();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
index 63e3f7f04..1412a932b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,18 @@
package org.apache.zookeeper.server.persistence;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
@@ -34,16 +46,8 @@ import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.junit.After;
import org.junit.Before;
-import org.junit.Assert;
import org.junit.Test;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
public class FileTxnSnapLogTest {
private File tmpDir;
@@ -65,7 +69,7 @@ public class FileTxnSnapLogTest {
@After
public void tearDown() throws Exception {
- if(tmpDir != null){
+ if (tmpDir != null) {
TestUtils.deleteFileRecursively(tmpDir);
}
this.tmpDir = null;
@@ -96,29 +100,32 @@ public class FileTxnSnapLogTest {
snapVersionDir = createVersionDir(snapDir);
// transaction log files in log dir
- createLogFile(logVersionDir,1);
- createLogFile(logVersionDir,2);
+ createLogFile(logVersionDir, 1);
+ createLogFile(logVersionDir, 2);
// snapshot files in snap dir
- createSnapshotFile(snapVersionDir,1);
- createSnapshotFile(snapVersionDir,2);
+ createSnapshotFile(snapVersionDir, 1);
+ createSnapshotFile(snapVersionDir, 2);
}
private void singleDirSetupWithCorrectFiles() throws IOException {
logVersionDir = createVersionDir(logDir);
// transaction log and snapshot files in the same dir
- createLogFile(logVersionDir,1);
- createLogFile(logVersionDir,2);
- createSnapshotFile(logVersionDir,1);
- createSnapshotFile(logVersionDir,2);
+ createLogFile(logVersionDir, 1);
+ createLogFile(logVersionDir, 2);
+ createSnapshotFile(logVersionDir, 1);
+ createSnapshotFile(logVersionDir, 2);
}
private FileTxnSnapLog createFileTxnSnapLogWithNoAutoCreateDataDir(File logDir, File snapDir) throws IOException {
return createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "false");
}
- private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDataDir(File logDir, File snapDir, String autoCreateValue) throws IOException {
+ private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDataDir(
+ File logDir,
+ File snapDir,
+ String autoCreateValue) throws IOException {
String priorAutocreateDirValue = System.getProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE);
System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE, autoCreateValue);
FileTxnSnapLog fileTxnSnapLog;
@@ -134,7 +141,10 @@ public class FileTxnSnapLogTest {
return fileTxnSnapLog;
}
- private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDB(File logDir, File snapDir, String autoCreateValue) throws IOException {
+ private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDB(
+ File logDir,
+ File snapDir,
+ String autoCreateValue) throws IOException {
String priorAutocreateDBValue = System.getProperty(FileTxnSnapLog.ZOOKEEPER_DB_AUTOCREATE);
System.setProperty(FileTxnSnapLog.ZOOKEEPER_DB_AUTOCREATE, autoCreateValue);
FileTxnSnapLog fileTxnSnapLog;
@@ -156,15 +166,15 @@ public class FileTxnSnapLogTest {
*/
@Test
public void testWithAutoCreateDataDir() throws IOException {
- Assert.assertFalse("log directory already exists", logDir.exists());
- Assert.assertFalse("snapshot directory already exists", snapDir.exists());
+ assertFalse("log directory already exists", logDir.exists());
+ assertFalse("snapshot directory already exists", snapDir.exists());
FileTxnSnapLog fileTxnSnapLog = createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "true");
- Assert.assertTrue(logDir.exists());
- Assert.assertTrue(snapDir.exists());
- Assert.assertTrue(fileTxnSnapLog.getDataDir().exists());
- Assert.assertTrue(fileTxnSnapLog.getSnapDir().exists());
+ assertTrue(logDir.exists());
+ assertTrue(snapDir.exists());
+ assertTrue(fileTxnSnapLog.getDataDir().exists());
+ assertTrue(fileTxnSnapLog.getSnapDir().exists());
}
/**
@@ -173,22 +183,26 @@ public class FileTxnSnapLogTest {
*/
@Test(expected = FileTxnSnapLog.DatadirException.class)
public void testWithoutAutoCreateDataDir() throws Exception {
- Assert.assertFalse("log directory already exists", logDir.exists());
- Assert.assertFalse("snapshot directory already exists", snapDir.exists());
+ assertFalse("log directory already exists", logDir.exists());
+ assertFalse("snapshot directory already exists", snapDir.exists());
try {
createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "false");
} catch (FileTxnSnapLog.DatadirException e) {
- Assert.assertFalse(logDir.exists());
- Assert.assertFalse(snapDir.exists());
+ assertFalse(logDir.exists());
+ assertFalse(snapDir.exists());
// rethrow exception
throw e;
}
- Assert.fail("Expected exception from FileTxnSnapLog");
+ fail("Expected exception from FileTxnSnapLog");
}
- private void attemptAutoCreateDB(File dataDir, File snapDir, Map<Long, Integer> sessions,
- String autoCreateValue, long expectedValue) throws IOException {
+ private void attemptAutoCreateDB(
+ File dataDir,
+ File snapDir,
+ Map<Long, Integer> sessions,
+ String autoCreateValue,
+ long expectedValue) throws IOException {
sessions.clear();
FileTxnSnapLog fileTxnSnapLog = createFileTxnSnapLogWithAutoCreateDB(dataDir, snapDir, autoCreateValue);
@@ -199,23 +213,23 @@ public class FileTxnSnapLogTest {
// empty by default
}
});
- Assert.assertEquals("unexpected zxid", expectedValue, zxid);
+ assertEquals("unexpected zxid", expectedValue, zxid);
}
@Test
public void testAutoCreateDB() throws IOException {
- Assert.assertTrue("cannot create log directory", logDir.mkdir());
- Assert.assertTrue("cannot create snapshot directory", snapDir.mkdir());
+ assertTrue("cannot create log directory", logDir.mkdir());
+ assertTrue("cannot create snapshot directory", snapDir.mkdir());
File initFile = new File(logDir, "initialize");
- Assert.assertFalse("initialize file already exists", initFile.exists());
+ assertFalse("initialize file already exists", initFile.exists());
Map<Long, Integer> sessions = new ConcurrentHashMap<>();
- attemptAutoCreateDB(logDir, snapDir, sessions,"false", -1L);
- attemptAutoCreateDB(logDir, snapDir, sessions,"true", 0L);
+ attemptAutoCreateDB(logDir, snapDir, sessions, "false", -1L);
+ attemptAutoCreateDB(logDir, snapDir, sessions, "true", 0L);
- Assert.assertTrue("cannot create initialize file", initFile.createNewFile());
- attemptAutoCreateDB(logDir, snapDir, sessions,"false", 0L);
+ assertTrue("cannot create initialize file", initFile.createNewFile());
+ attemptAutoCreateDB(logDir, snapDir, sessions, "false", 0L);
}
@Test
@@ -230,7 +244,7 @@ public class FileTxnSnapLogTest {
fileTxnSnapLog.append(req);
fileTxnSnapLog.commit();
long syncElapsedTime = fileTxnSnapLog.getTxnLogElapsedSyncTime();
- Assert.assertNotEquals("Did not update syncElapsedTime!", -1L, syncElapsedTime);
+ assertNotEquals("Did not update syncElapsedTime!", -1L, syncElapsedTime);
} finally {
fileTxnSnapLog.close();
}
@@ -243,7 +257,7 @@ public class FileTxnSnapLogTest {
try {
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
} catch (FileTxnSnapLog.LogDirContentCheckException | FileTxnSnapLog.SnapDirContentCheckException e) {
- Assert.fail("Should not throw ContentCheckException.");
+ fail("Should not throw ContentCheckException.");
}
}
@@ -254,7 +268,7 @@ public class FileTxnSnapLogTest {
try {
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, logDir);
} catch (FileTxnSnapLog.LogDirContentCheckException | FileTxnSnapLog.SnapDirContentCheckException e) {
- Assert.fail("Should not throw ContentCheckException.");
+ fail("Should not throw ContentCheckException.");
}
}
@@ -263,8 +277,8 @@ public class FileTxnSnapLogTest {
twoDirSetupWithCorrectFiles();
// add snapshot files to the log version dir
- createSnapshotFile(logVersionDir,3);
- createSnapshotFile(logVersionDir,4);
+ createSnapshotFile(logVersionDir, 3);
+ createSnapshotFile(logVersionDir, 4);
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
}
@@ -274,8 +288,8 @@ public class FileTxnSnapLogTest {
twoDirSetupWithCorrectFiles();
// add transaction log files to the snap version dir
- createLogFile(snapVersionDir,3);
- createLogFile(snapVersionDir,4);
+ createLogFile(snapVersionDir, 3);
+ createLogFile(snapVersionDir, 4);
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
}
@@ -333,9 +347,10 @@ public class FileTxnSnapLogTest {
followerDataTree.processTxn(hdr1, txn1);
DataNode a1 = leaderDataTree.getNode("/a1");
- Assert.assertNotNull(a1);
- Assert.assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, leaderDataTree.getACL(a1));
+ assertNotNull(a1);
+ assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, leaderDataTree.getACL(a1));
- Assert.assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, followerDataTree.getACL(a1));
+ assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, followerDataTree.getACL(a1));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
index 3b8cb2a7f..d884d1e06 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,12 +18,15 @@
package org.apache.zookeeper.server.persistence;
+import static org.apache.zookeeper.test.ClientBase.createTmpDir;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
@@ -31,9 +34,6 @@ import org.apache.jute.OutputArchive;
import org.apache.zookeeper.server.persistence.SnapStream.StreamMode;
import org.junit.After;
import org.junit.Test;
-import org.junit.Assert;
-
-import static org.apache.zookeeper.test.ClientBase.createTmpDir;
public class SnapStreamTest {
@@ -45,34 +45,22 @@ public class SnapStreamTest {
@Test
public void testStreamMode() {
- Assert.assertEquals(StreamMode.CHECKED.getName(), "");
- Assert.assertEquals(StreamMode.CHECKED.getFileExtension(), "");
- Assert.assertEquals(StreamMode.CHECKED, StreamMode.fromString("name"));
- Assert.assertEquals(StreamMode.GZIP.getName(), "gz");
- Assert.assertEquals(StreamMode.GZIP.getFileExtension(), ".gz");
- Assert.assertEquals(StreamMode.GZIP, StreamMode.fromString("gz"));
- Assert.assertEquals(StreamMode.SNAPPY.getName(), "snappy");
- Assert.assertEquals(StreamMode.SNAPPY.getFileExtension(), ".snappy");
- Assert.assertEquals(StreamMode.SNAPPY, StreamMode.fromString("snappy"));
+ assertEquals(StreamMode.CHECKED.getName(), "");
+ assertEquals(StreamMode.CHECKED.getFileExtension(), "");
+ assertEquals(StreamMode.CHECKED, StreamMode.fromString("name"));
+ assertEquals(StreamMode.GZIP.getName(), "gz");
+ assertEquals(StreamMode.GZIP.getFileExtension(), ".gz");
+ assertEquals(StreamMode.GZIP, StreamMode.fromString("gz"));
+ assertEquals(StreamMode.SNAPPY.getName(), "snappy");
+ assertEquals(StreamMode.SNAPPY.getFileExtension(), ".snappy");
+ assertEquals(StreamMode.SNAPPY, StreamMode.fromString("snappy"));
}
@Test
public void testGetStreamMode() {
- Assert.assertEquals(
- "expected to return un-compressed stream",
- StreamMode.CHECKED,
- SnapStream.getStreamMode("snapshot.180000e3a2")
- );
- Assert.assertEquals(
- "expected to return snappy stream",
- StreamMode.SNAPPY,
- SnapStream.getStreamMode("snapshot.180000e3a2.snappy")
- );
- Assert.assertEquals(
- "expected to return gzip stream",
- StreamMode.GZIP,
- SnapStream.getStreamMode("snapshot.180000e3a2.gz")
- );
+ assertEquals("expected to return un-compressed stream", StreamMode.CHECKED, SnapStream.getStreamMode("snapshot.180000e3a2"));
+ assertEquals("expected to return snappy stream", StreamMode.SNAPPY, SnapStream.getStreamMode("snapshot.180000e3a2.snappy"));
+ assertEquals("expected to return gzip stream", StreamMode.GZIP, SnapStream.getStreamMode("snapshot.180000e3a2.gz"));
}
@Test
@@ -104,15 +92,14 @@ public class SnapStreamTest {
os.flush();
os.close();
- Assert.assertTrue(SnapStream.isValidSnapshot(file));
+ assertTrue(SnapStream.isValidSnapshot(file));
// deserialize with gzip stream
CheckedInputStream is = SnapStream.getInputStream(file);
InputArchive ia = BinaryInputArchive.getArchive(is);
FileHeader restoredHeader = new FileHeader();
restoredHeader.deserialize(ia, "fileheader");
- Assert.assertEquals(
- "magic not the same", restoredHeader, header);
+ assertEquals("magic not the same", restoredHeader, header);
SnapStream.checkSealIntegrity(is, ia);
}
@@ -127,15 +114,16 @@ public class SnapStreamTest {
os.write(1);
os.flush();
os.close();
- Assert.assertFalse(SnapStream.isValidSnapshot(file));
+ assertFalse(SnapStream.isValidSnapshot(file));
}
@Test
public void testInvalidSnapshot() throws IOException {
- Assert.assertFalse(SnapStream.isValidSnapshot(null));
+ assertFalse(SnapStream.isValidSnapshot(null));
checkInvalidSnapshot("snapshot.180000e3a2");
checkInvalidSnapshot("snapshot.180000e3a2.gz");
checkInvalidSnapshot("snapshot.180000e3a2.snappy");
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
index 60b3ea6ec..20d6fe8a9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,12 +18,10 @@
package org.apache.zookeeper.server.persistence;
-import org.apache.commons.io.FileUtils;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
@@ -32,16 +30,15 @@ import java.io.PrintStream;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
+import org.apache.commons.io.FileUtils;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class TxnLogToolkitTest {
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@@ -152,4 +149,5 @@ public class TxnLogToolkitTest {
output = outContent.toString();
assertThat(output, not(containsString("CRC ERROR")));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java
index 8435e856a..9fb9cfb2b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,11 +18,11 @@
package org.apache.zookeeper.server.quorum;
-import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
+import org.junit.Test;
public class BufferStatsTest {
+
@Test
public void testSetProposalSizeSetMinMax() {
BufferStats stats = new BufferStats();
@@ -55,4 +55,5 @@ public class BufferStatsTest {
assertEquals(-1, stats.getMinBufferSize());
assertEquals(-1, stats.getMaxBufferSize());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java
index 276f35f47..013ca53f8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,11 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
@@ -25,6 +30,7 @@ import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
+import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@@ -35,66 +41,55 @@ import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;
+import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
-import javax.net.ssl.HandshakeCompletedListener;
-
-import org.apache.zookeeper.common.QuorumX509Util;
-import org.apache.zookeeper.common.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager.Message;
+import org.apache.zookeeper.common.QuorumX509Util;
+import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.server.quorum.QuorumCnxManager.InitialMessage;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
+import org.apache.zookeeper.server.quorum.QuorumCnxManager.Message;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.FLENewEpochTest;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class CnxManagerTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLENewEpochTest.class);
protected static final int THRESHOLD = 4;
int count;
- Map<Long,QuorumServer> peers;
- File peerTmpdir[];
- int peerQuorumPort[];
- int peerClientPort[];
+ Map<Long, QuorumServer> peers;
+ File[] peerTmpdir;
+ int[] peerQuorumPort;
+ int[] peerClientPort;
@Before
public void setUp() throws Exception {
this.count = 3;
- this.peers = new HashMap<Long,QuorumServer>(count);
+ this.peers = new HashMap<Long, QuorumServer>(count);
peerTmpdir = new File[count];
peerQuorumPort = new int[count];
peerClientPort = new int[count];
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
peerQuorumPort[i] = PortAssignment.unique();
peerClientPort[i] = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(
- "127.0.0.1", peerQuorumPort[i]),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", peerClientPort[i])));
+ peers.put((long) i, new QuorumServer(i, new InetSocketAddress("127.0.0.1", peerQuorumPort[i]), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", peerClientPort[i])));
peerTmpdir[i] = ClientBase.createTmpDir();
}
}
- ByteBuffer createMsg(int state, long leader, long zxid, long epoch){
- byte requestBytes[] = new byte[28];
+ ByteBuffer createMsg(int state, long leader, long zxid, long epoch) {
+ byte[] requestBytes = new byte[28];
ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
/*
@@ -113,16 +108,16 @@ public class CnxManagerTest extends ZKTestCase {
class CnxManagerThread extends Thread {
boolean failed;
- CnxManagerThread(){
+ CnxManagerThread() {
failed = false;
}
- public void run(){
+ public void run() {
try {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[0], peerTmpdir[0], peerClientPort[0], 3, 0, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -133,12 +128,14 @@ public class CnxManagerTest extends ZKTestCase {
Message m = null;
int numRetries = 1;
- while((m == null) && (numRetries++ <= THRESHOLD)){
+ while ((m == null) && (numRetries++ <= THRESHOLD)) {
m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
- if(m == null) cnxManager.connectAll();
+ if (m == null) {
+ cnxManager.connectAll();
+ }
}
- if(numRetries > THRESHOLD){
+ if (numRetries > THRESHOLD) {
failed = true;
return;
}
@@ -146,15 +143,15 @@ public class CnxManagerTest extends ZKTestCase {
cnxManager.testInitiateConnection(sid);
m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
- if(m == null){
+ if (m == null) {
failed = true;
- return;
}
} catch (Exception e) {
LOG.error("Exception while running mock thread", e);
- Assert.fail("Unexpected exception");
+ fail("Unexpected exception");
}
}
+
}
@Test
@@ -166,7 +163,7 @@ public class CnxManagerTest extends ZKTestCase {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -176,22 +173,25 @@ public class CnxManagerTest extends ZKTestCase {
Message m = null;
int numRetries = 1;
- while((m == null) && (numRetries++ <= THRESHOLD)){
+ while ((m == null) && (numRetries++ <= THRESHOLD)) {
m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
- if(m == null) cnxManager.connectAll();
+ if (m == null) {
+ cnxManager.connectAll();
+ }
}
- Assert.assertTrue("Exceeded number of retries", numRetries <= THRESHOLD);
+ assertTrue("Exceeded number of retries", numRetries <= THRESHOLD);
thread.join(5000);
if (thread.isAlive()) {
- Assert.fail("Thread didn't join");
+ fail("Thread didn't join");
} else {
- if(thread.failed)
- Assert.fail("Did not receive expected message");
+ if (thread.failed) {
+ fail("Did not receive expected message");
+ }
}
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
@Test
@@ -203,17 +203,13 @@ public class CnxManagerTest extends ZKTestCase {
LOG.info("This is the dead address I'm trying: " + deadAddress);
- peers.put(Long.valueOf(2),
- new QuorumServer(2,
- new InetSocketAddress(deadAddress, deadPort),
- new InetSocketAddress(deadAddress, PortAssignment.unique()),
- new InetSocketAddress(deadAddress, PortAssignment.unique())));
+ peers.put(2L, new QuorumServer(2, new InetSocketAddress(deadAddress, deadPort), new InetSocketAddress(deadAddress, PortAssignment.unique()), new InetSocketAddress(deadAddress, PortAssignment.unique())));
peerTmpdir[2] = ClientBase.createTmpDir();
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -223,9 +219,11 @@ public class CnxManagerTest extends ZKTestCase {
cnxManager.toSend(2L, createMsg(ServerState.LOOKING.ordinal(), 1, -1, 1));
long end = Time.currentElapsedTime();
- if((end - begin) > 6000) Assert.fail("Waited more than necessary");
+ if ((end - begin) > 6000) {
+ fail("Waited more than necessary");
+ }
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/**
@@ -241,7 +239,7 @@ public class CnxManagerTest extends ZKTestCase {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -259,12 +257,11 @@ public class CnxManagerTest extends ZKTestCase {
DataOutputStream dout = new DataOutputStream(sc.socket().getOutputStream());
dout.writeLong(QuorumCnxManager.PROTOCOL_VERSION);
dout.writeLong(2);
- String addr = otherAddr.getHostString()+ ":" + otherAddr.getPort();
+ String addr = otherAddr.getHostString() + ":" + otherAddr.getPort();
byte[] addr_bytes = addr.getBytes();
dout.writeInt(addr_bytes.length);
dout.write(addr_bytes);
dout.flush();
-
ByteBuffer msgBuffer = ByteBuffer.wrap(new byte[4]);
msgBuffer.putInt(-20);
@@ -273,26 +270,26 @@ public class CnxManagerTest extends ZKTestCase {
Thread.sleep(1000);
- try{
+ try {
/*
* Write a number of times until it
* detects that the socket is broken.
*/
- for(int i = 0; i < 100; i++){
+ for (int i = 0; i < 100; i++) {
msgBuffer.position(0);
sc.write(msgBuffer);
}
- Assert.fail("Socket has not been closed");
+ fail("Socket has not been closed");
} catch (Exception e) {
LOG.info("Socket has been closed as expected");
}
peer.shutdown();
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/**
- * Test for bug described in {@link https://issues.apache.org/jira/browse/ZOOKEEPER-3320}.
+ * Test for bug described in https://issues.apache.org/jira/browse/ZOOKEEPER-3320.
* Test create peer with address which contains unresolvable DNS name,
* leader election listener thread should stop after N errors.
*
@@ -300,13 +297,10 @@ public class CnxManagerTest extends ZKTestCase {
*/
@Test
public void testCnxManagerListenerThreadConfigurableRetry() throws Exception {
- final Map<Long,QuorumServer> unresolvablePeers = new HashMap<>();
+ final Map<Long, QuorumServer> unresolvablePeers = new HashMap<>();
final long myid = 1L;
unresolvablePeers.put(myid, new QuorumServer(myid, "unresolvable-domain.org:2182:2183;2181"));
- final QuorumPeer peer = new QuorumPeer(unresolvablePeers,
- ClientBase.createTmpDir(),
- ClientBase.createTmpDir(),
- 2181, 3, myid, 1000, 2, 2, 2);
+ final QuorumPeer peer = new QuorumPeer(unresolvablePeers, ClientBase.createTmpDir(), ClientBase.createTmpDir(), 2181, 3, myid, 1000, 2, 2, 2);
final QuorumCnxManager cnxManager = peer.createCnxnManager();
final QuorumCnxManager.Listener listener = cnxManager.listener;
final AtomicBoolean errorHappend = new AtomicBoolean();
@@ -315,25 +309,25 @@ public class CnxManagerTest extends ZKTestCase {
// listener thread should stop and throws error which notify QuorumPeer about error.
// QuorumPeer should start shutdown process
listener.join(15000); // set wait time, if listener contains bug and thread not stops.
- Assert.assertFalse(listener.isAlive());
- Assert.assertTrue(errorHappend.get());
- Assert.assertFalse(QuorumPeer.class.getSimpleName() + " not stopped after "
- + "listener thread death", listener.isAlive());
+ assertFalse(listener.isAlive());
+ assertTrue(errorHappend.get());
+ assertFalse(QuorumPeer.class.getSimpleName()
+ + " not stopped after "
+ + "listener thread death", listener.isAlive());
}
/**
* Tests a bug in QuorumCnxManager that causes a NPE when a 3.4.6
- * observer connects to a 3.5.0 server.
+ * observer connects to a 3.5.0 server.
* see https://issues.apache.org/jira/browse/ZOOKEEPER-1789
- *
+ *
* @throws Exception
*/
@Test
public void testCnxManagerNPE() throws Exception {
// the connecting peer (id = 2) is a 3.4.6 observer
peers.get(2L).type = LearnerType.OBSERVER;
- QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1],
- peerClientPort[1], 3, 1, 1000, 2, 2, 2);
+ QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
if (listener != null) {
@@ -368,11 +362,11 @@ public class CnxManagerTest extends ZKTestCase {
sc.write(msgBuffer);
Message m = cnxManager.pollRecvQueue(1000, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(m);
+ assertNotNull(m);
peer.shutdown();
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/*
@@ -383,7 +377,7 @@ public class CnxManagerTest extends ZKTestCase {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 2000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -398,9 +392,11 @@ public class CnxManagerTest extends ZKTestCase {
// Read without sending data. Verify timeout.
cnxManager.receiveConnection(sock);
long end = Time.currentElapsedTime();
- if((end - begin) > ((peer.getSyncLimit() * peer.getTickTime()) + 500)) Assert.fail("Waited more than necessary");
+ if ((end - begin) > ((peer.getSyncLimit() * peer.getTickTime()) + 500)) {
+ fail("Waited more than necessary");
+ }
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/**
@@ -416,7 +412,8 @@ public class CnxManagerTest extends ZKTestCase {
return new SSLSocket() {
@Override
- public void connect(SocketAddress endpoint, int timeout) {}
+ public void connect(SocketAddress endpoint, int timeout) {
+ }
@Override
public void startHandshake() throws IOException {
@@ -428,19 +425,19 @@ public class CnxManagerTest extends ZKTestCase {
closeLatch.countDown();
}
- public String [] getSupportedCipherSuites() {
+ public String[] getSupportedCipherSuites() {
throw new UnsupportedOperationException();
}
- public String [] getEnabledCipherSuites() {
+ public String[] getEnabledCipherSuites() {
throw new UnsupportedOperationException();
}
- public String [] getSupportedProtocols() {
+ public String[] getSupportedProtocols() {
throw new UnsupportedOperationException();
}
- public String [] getEnabledProtocols() {
+ public String[] getEnabledProtocols() {
throw new UnsupportedOperationException();
}
@@ -448,24 +445,39 @@ public class CnxManagerTest extends ZKTestCase {
throw new UnsupportedOperationException();
}
- public void setEnabledCipherSuites(String suites []) {}
- public void setEnabledProtocols(String protocols[]) {}
- public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {}
- public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {}
- public void setUseClientMode(boolean mode) {}
- public boolean getUseClientMode() { return true; }
- public void setNeedClientAuth(boolean need) {}
- public boolean getNeedClientAuth() { return true; }
- public void setWantClientAuth(boolean want) {}
- public boolean getWantClientAuth() { return true; }
- public void setEnableSessionCreation(boolean flag) {}
- public boolean getEnableSessionCreation() { return true; }
+ public void setEnabledCipherSuites(String[] suites) {
+ }
+ public void setEnabledProtocols(String[] protocols) {
+ }
+ public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {
+ }
+ public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {
+ }
+ public void setUseClientMode(boolean mode) {
+ }
+ public boolean getUseClientMode() {
+ return true;
+ }
+ public void setNeedClientAuth(boolean need) {
+ }
+ public boolean getNeedClientAuth() {
+ return true;
+ }
+ public void setWantClientAuth(boolean want) {
+ }
+ public boolean getWantClientAuth() {
+ return true;
+ }
+ public void setEnableSessionCreation(boolean flag) {
+ }
+ public boolean getEnableSessionCreation() {
+ return true;
+ }
};
}
};
- QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[0], peerTmpdir[0],
- peerClientPort[0], 3, 0, 2000, 2, 2, 2) {
+ QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[0], peerTmpdir[0], peerClientPort[0], 3, 0, 2000, 2, 2, 2) {
@Override
public QuorumX509Util createX509Util() {
return mockedX509Util;
@@ -475,7 +487,7 @@ public class CnxManagerTest extends ZKTestCase {
peer.setSslQuorum(true);
QuorumCnxManager cnxManager = peer.createCnxnManager();
cnxManager.connectOne(1, peers.get(1L).electionAddr);
- Assert.assertTrue(closeLatch.await(1, TimeUnit.SECONDS));
+ assertTrue(closeLatch.await(1, TimeUnit.SECONDS));
}
/*
@@ -486,35 +498,29 @@ public class CnxManagerTest extends ZKTestCase {
ArrayList<QuorumPeer> peerList = new ArrayList<QuorumPeer>();
try {
for (int sid = 0; sid < 3; sid++) {
- QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[sid],
- peerTmpdir[sid], peerClientPort[sid], 3, sid, 1000, 2,
- 2, 2);
+ QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[sid], peerTmpdir[sid], peerClientPort[sid], 3, sid, 1000, 2, 2, 2);
LOG.info("Starting peer {}", peer.getId());
peer.start();
peerList.add(sid, peer);
}
String failure = verifyThreadCount(peerList, 4);
- Assert.assertNull(failure, failure);
+ assertNull(failure, failure);
for (int myid = 0; myid < 3; myid++) {
for (int i = 0; i < 5; i++) {
// halt one of the listeners and verify count
QuorumPeer peer = peerList.get(myid);
- LOG.info("Round {}, halting peer ",
- new Object[] { i, peer.getId() });
+ LOG.info("Round {}, halting peer {}", i, peer.getId());
peer.shutdown();
peerList.remove(myid);
failure = verifyThreadCount(peerList, 2);
- Assert.assertNull(failure, failure);
+ assertNull(failure, failure);
// Restart halted node and verify count
- peer = new QuorumPeer(peers, peerTmpdir[myid],
- peerTmpdir[myid], peerClientPort[myid], 3, myid,
- 1000, 2, 2, 2);
- LOG.info("Round {}, restarting peer ",
- new Object[] { i, peer.getId() });
+ peer = new QuorumPeer(peers, peerTmpdir[myid], peerTmpdir[myid], peerClientPort[myid], 3, myid, 1000, 2, 2, 2);
+ LOG.info("Round {}, restarting peer {}", i, peer.getId());
peer.start();
peerList.add(myid, peer);
failure = verifyThreadCount(peerList, 4);
- Assert.assertNull(failure, failure);
+ assertNull(failure, failure);
}
}
} finally {
@@ -528,9 +534,7 @@ public class CnxManagerTest extends ZKTestCase {
* Returns null on success, otw the message assoc with the failure
* @throws InterruptedException
*/
- public String verifyThreadCount(ArrayList<QuorumPeer> peerList, long ecnt)
- throws InterruptedException
- {
+ public String verifyThreadCount(ArrayList<QuorumPeer> peerList, long ecnt) throws InterruptedException {
String failure = null;
for (int i = 0; i < 480; i++) {
Thread.sleep(500);
@@ -549,8 +553,9 @@ public class CnxManagerTest extends ZKTestCase {
long cnt = cnxManager.getThreadCount();
if (cnt != ecnt) {
return new Date()
- + " Incorrect number of Worker threads for sid=" + myid
- + " expected " + ecnt + " found " + cnt;
+ + " Incorrect number of Worker threads for sid=" + myid
+ + " expected " + ecnt
+ + " found " + cnt;
}
}
return null;
@@ -578,8 +583,9 @@ public class CnxManagerTest extends ZKTestCase {
// now parse it
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(-65530L, din);
- Assert.fail("bad protocol version accepted");
- } catch (InitialMessage.InitialMessageException ex) {}
+ fail("bad protocol version accepted");
+ } catch (InitialMessage.InitialMessageException ex) {
+ }
// message too long
try {
@@ -593,8 +599,9 @@ public class CnxManagerTest extends ZKTestCase {
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(QuorumCnxManager.PROTOCOL_VERSION, din);
- Assert.fail("long message accepted");
- } catch (InitialMessage.InitialMessageException ex) {}
+ fail("long message accepted");
+ } catch (InitialMessage.InitialMessageException ex) {
+ }
// bad hostport string
try {
@@ -608,8 +615,9 @@ public class CnxManagerTest extends ZKTestCase {
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(QuorumCnxManager.PROTOCOL_VERSION, din);
- Assert.fail("bad hostport accepted");
- } catch (InitialMessage.InitialMessageException ex) {}
+ fail("bad hostport accepted");
+ } catch (InitialMessage.InitialMessageException ex) {
+ }
// good message
try {
@@ -625,15 +633,16 @@ public class CnxManagerTest extends ZKTestCase {
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(QuorumCnxManager.PROTOCOL_VERSION, din);
} catch (InitialMessage.InitialMessageException ex) {
- Assert.fail(ex.toString());
+ fail(ex.toString());
}
}
private String createLongString(int size) {
StringBuilder sb = new StringBuilder(size);
- for (int i=0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
sb.append('x');
}
return sb.toString();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java
index 95889ef1d..7d342a0d7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -28,7 +31,6 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.CreateMode;
@@ -44,15 +46,14 @@ import org.apache.zookeeper.server.RequestProcessor;
import org.apache.zookeeper.server.WorkerService;
import org.apache.zookeeper.server.ZooKeeperServerListener;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommitProcessorConcurrencyTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(CommitProcessorConcurrencyTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(CommitProcessorConcurrencyTest.class);
BlockingQueue<Request> processedRequests;
MockCommitProcessor processor;
@@ -74,6 +75,7 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
// This queue is infinite if we use "poll" to get requests, but returns a
// finite size when asked.
class MockRequestsQueue extends LinkedBlockingQueue<Request> {
+
private static final long serialVersionUID = 1L;
int readReqId = 0;
@@ -81,12 +83,10 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
public Request poll() {
readReqId++;
try {
- return newRequest(new GetDataRequest("/", false),
- OpCode.getData, readReqId % 50, readReqId);
+ return newRequest(new GetDataRequest("/", false), OpCode.getData, readReqId % 50, readReqId);
} catch (IOException e) {
e.printStackTrace();
}
- ;
return null;
}
@@ -94,13 +94,14 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
public int size() {
return 42;
}
+
}
class MockCommitProcessor extends CommitProcessor {
+
MockCommitProcessor() {
super(new RequestProcessor() {
- public void processRequest(Request request)
- throws RequestProcessorException {
+ public void processRequest(Request request) throws RequestProcessorException {
processedRequests.offer(request);
}
@@ -110,20 +111,19 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
@Override
public void notifyStopping(String threadName, int errorCode) {
- Assert.fail("Commit processor crashed " + errorCode);
+ fail("Commit processor crashed " + errorCode);
}
});
}
public void initThreads(int poolSize) {
this.stopped = false;
- this.workerPool = new WorkerService("CommitProcWork", poolSize,
- true);
+ this.workerPool = new WorkerService("CommitProcWork", poolSize, true);
}
+
}
- private Request newRequest(Record rec, int type, int sessionId, int xid)
- throws IOException {
+ private Request newRequest(Record rec, int type, int sessionId, int xid) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
rec.serialize(boa, "request");
@@ -137,15 +137,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* according to the order of the session (first read, then the write).
*/
@Test
- public void committedAndUncommittedOfTheSameSessionRaceTest()
- throws Exception {
+ public void committedAndUncommittedOfTheSameSessionRaceTest() throws Exception {
final String path = "/testCvsUCRace";
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x0, 0);
- Request writeReq = newRequest(
- new SetDataRequest(path, new byte[16], -1), OpCode.setData, 0x0,
- 1);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x0, 0);
+ Request writeReq = newRequest(new SetDataRequest(path, new byte[16], -1), OpCode.setData, 0x0, 1);
processor.committedRequests.add(writeReq);
processor.queuedRequests.add(readReq);
@@ -156,17 +152,13 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
- Assert.assertTrue(
- "Request was not processed " + readReq + " instead "
- + processedRequests.peek(),
- processedRequests.peek() != null
- && processedRequests.peek().equals(readReq));
+ assertTrue(
+ "Request was not processed " + readReq + " instead " + processedRequests.peek(),
+ processedRequests.peek() != null && processedRequests.peek().equals(readReq));
processedRequests.poll();
- Assert.assertTrue(
- "Request was not processed " + writeReq + " instead "
- + processedRequests.peek(),
- processedRequests.peek() != null
- && processedRequests.peek().equals(writeReq));
+ assertTrue(
+ "Request was not processed " + writeReq + " instead " + processedRequests.peek(),
+ processedRequests.peek() != null && processedRequests.peek().equals(writeReq));
}
/**
@@ -178,24 +170,30 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* uncommited requests, followed by the reads are processed.
*/
@Test
- public void processAsMuchUncommittedRequestsAsPossibleTest()
- throws Exception {
+ public void processAsMuchUncommittedRequestsAsPossibleTest() throws Exception {
final String path = "/testAsMuchAsPossible";
List<Request> shouldBeProcessed = new LinkedList<Request>();
Set<Request> shouldNotBeProcessed = new HashSet<Request>();
for (int sessionId = 1; sessionId <= 5; ++sessionId) {
for (int readReqId = 1; readReqId <= sessionId; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionId, readReqId);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionId, readReqId);
shouldBeProcessed.add(readReq);
processor.queuedRequests.add(readReq);
}
Request writeReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionId, sessionId + 1);
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionId, sessionId + 2);
+ new CreateRequest(
+ path,
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionId,
+ sessionId + 1);
+ Request readReq = newRequest(
+ new GetDataRequest(path, false),
+ OpCode.getData,
+ sessionId,
+ sessionId + 2);
processor.queuedRequests.add(writeReq);
processor.queuedWriteRequests.add(writeReq);
processor.queuedRequests.add(readReq);
@@ -211,10 +209,8 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
for (Request r : shouldBeProcessed) {
LOG.error("Did not process " + r);
}
- Assert.assertTrue("Not all requests were processed",
- shouldBeProcessed.isEmpty());
- Assert.assertFalse("Processed a wrong request",
- shouldNotBeProcessed.removeAll(processedRequests));
+ assertTrue("Not all requests were processed", shouldBeProcessed.isEmpty());
+ assertFalse("Processed a wrong request", shouldNotBeProcessed.removeAll(processedRequests));
}
/**
@@ -225,23 +221,22 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* executed after the write, before any other write, along with new reads.
*/
@Test
- public void processAllFollowingUncommittedAfterFirstCommitTest()
- throws Exception {
+ public void processAllFollowingUncommittedAfterFirstCommitTest() throws Exception {
final String path = "/testUncommittedFollowingCommited";
Set<Request> shouldBeInPending = new HashSet<Request>();
Set<Request> shouldBeProcessedAfterPending = new HashSet<Request>();
Request writeReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x1, 1);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x1,
+ 1);
processor.queuedRequests.add(writeReq);
processor.queuedWriteRequests.add(writeReq);
shouldBeInPending.add(writeReq);
for (int readReqId = 2; readReqId <= 5; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, readReqId);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, readReqId);
processor.queuedRequests.add(readReq);
shouldBeInPending.add(readReq);
shouldBeProcessedAfterPending.add(readReq);
@@ -250,21 +245,15 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
- Assert.assertTrue("Processed without waiting for commit",
- processedRequests.isEmpty());
- Assert.assertTrue("Did not handled all of queuedRequests' requests",
- processor.queuedRequests.isEmpty());
- Assert.assertTrue("Removed from blockedQueuedRequests before commit",
- !processor.queuedWriteRequests.isEmpty());
-
- shouldBeInPending
- .removeAll(processor.pendingRequests.get(writeReq.sessionId));
+ assertTrue("Processed without waiting for commit", processedRequests.isEmpty());
+ assertTrue("Did not handled all of queuedRequests' requests", processor.queuedRequests.isEmpty());
+ assertTrue("Removed from blockedQueuedRequests before commit", !processor.queuedWriteRequests.isEmpty());
+
+ shouldBeInPending.removeAll(processor.pendingRequests.get(writeReq.sessionId));
for (Request r : shouldBeInPending) {
LOG.error("Should be in pending " + r);
}
- Assert.assertTrue(
- "Not all requests moved to pending from queuedRequests",
- shouldBeInPending.isEmpty());
+ assertTrue("Not all requests moved to pending from queuedRequests", shouldBeInPending.isEmpty());
processor.committedRequests.add(writeReq);
processor.stoppedMainLoop = true;
@@ -272,16 +261,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Did not process committed request",
- processor.committedRequests.isEmpty());
- Assert.assertTrue("Did not process committed request",
- processor.pendingRequests.isEmpty());
- Assert.assertTrue("Did not remove from blockedQueuedRequests",
- processor.queuedWriteRequests.isEmpty());
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Did not process committed request", processor.committedRequests.isEmpty());
+ assertTrue("Did not process committed request", processor.pendingRequests.isEmpty());
+ assertTrue("Did not remove from blockedQueuedRequests", processor.queuedWriteRequests.isEmpty());
}
/**
@@ -299,30 +283,37 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* in the last iteration, and all lists are empty.
*/
@Test
- public void processAllWritesMaxBatchSize()
- throws Exception {
+ public void processAllWritesMaxBatchSize() throws Exception {
final String path = "/processAllWritesMaxBatchSize";
HashSet<Request> shouldBeProcessedAfterPending = new HashSet<Request>();
Request writeReq = newRequest(
- new CreateRequest(path + "_1", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x1, 1);
+ new CreateRequest(
+ path + "_1",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x1,
+ 1);
processor.queuedRequests.add(writeReq);
processor.queuedWriteRequests.add(writeReq);
Request writeReq2 = newRequest(
- new CreateRequest(path + "_2", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x2, 1);
+ new CreateRequest(
+ path + "_2",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x2,
+ 1);
processor.queuedRequests.add(writeReq2);
processor.queuedWriteRequests.add(writeReq2);
for (int readReqId = 2; readReqId <= 5; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, readReqId);
- Request readReq2 = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x2, readReqId);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, readReqId);
+ Request readReq2 = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x2, readReqId);
processor.queuedRequests.add(readReq);
shouldBeProcessedAfterPending.add(readReq);
processor.queuedRequests.add(readReq2);
@@ -330,9 +321,14 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
}
Request writeReq3 = newRequest(
- new CreateRequest(path + "_3", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x2, 6);
+ new CreateRequest(
+ path + "_3",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x2,
+ 6);
processor.queuedRequests.add(writeReq3);
processor.queuedWriteRequests.add(writeReq3);
@@ -341,16 +337,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
CommitProcessor.setMaxCommitBatchSize(2);
processor.run();
- Assert.assertTrue("Processed without waiting for commit",
- processedRequests.isEmpty());
- Assert.assertTrue("Did not handled all of queuedRequests' requests",
- processor.queuedRequests.isEmpty());
- Assert.assertTrue("Removed from blockedQueuedRequests before commit",
- !processor.queuedWriteRequests.isEmpty());
- Assert.assertTrue("Missing session 1 in pending queue",
- processor.pendingRequests.containsKey(writeReq.sessionId));
- Assert.assertTrue("Missing session 2 in pending queue",
- processor.pendingRequests.containsKey(writeReq2.sessionId));
+ assertTrue("Processed without waiting for commit", processedRequests.isEmpty());
+ assertTrue("Did not handled all of queuedRequests' requests", processor.queuedRequests.isEmpty());
+ assertTrue("Removed from blockedQueuedRequests before commit", !processor.queuedWriteRequests.isEmpty());
+ assertTrue("Missing session 1 in pending queue", processor.pendingRequests.containsKey(writeReq.sessionId));
+ assertTrue("Missing session 2 in pending queue", processor.pendingRequests.containsKey(writeReq2.sessionId));
processor.committedRequests.add(writeReq);
processor.committedRequests.add(writeReq2);
@@ -361,33 +352,34 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Processed committed request",
- !processor.committedRequests.isEmpty());
- Assert.assertTrue("Removed commit for write req 3",
- processor.committedRequests.peek() == writeReq3);
- Assert.assertTrue("Processed committed request",
- !processor.pendingRequests.isEmpty());
- Assert.assertTrue("Missing session 2 in pending queue",
- processor.pendingRequests.containsKey(writeReq3.sessionId));
- Assert.assertTrue("Missing write 3 in pending queue",
- processor.pendingRequests.get(writeReq3.sessionId).peek() == writeReq3);
- Assert.assertTrue("Removed from blockedQueuedRequests",
- !processor.queuedWriteRequests.isEmpty());
- Assert.assertTrue("Removed write req 3 from blockedQueuedRequests",
- processor.queuedWriteRequests.peek() == writeReq3);
-
- Request readReq3 = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, 7);
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Processed committed request", !processor.committedRequests.isEmpty());
+ assertTrue("Removed commit for write req 3", processor.committedRequests.peek() == writeReq3);
+ assertTrue("Processed committed request", !processor.pendingRequests.isEmpty());
+ assertTrue("Missing session 2 in pending queue", processor.pendingRequests.containsKey(writeReq3.sessionId));
+ assertTrue(
+ "Missing write 3 in pending queue",
+ processor.pendingRequests.get(writeReq3.sessionId).peek() == writeReq3);
+ assertTrue(
+ "Removed from blockedQueuedRequests",
+ !processor.queuedWriteRequests.isEmpty());
+ assertTrue(
+ "Removed write req 3 from blockedQueuedRequests",
+ processor.queuedWriteRequests.peek() == writeReq3);
+
+ Request readReq3 = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, 7);
processor.queuedRequests.add(readReq3);
shouldBeProcessedAfterPending.add(readReq3);
Request writeReq4 = newRequest(
- new CreateRequest(path + "_4", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x2, 7);
+ new CreateRequest(
+ path + "_4",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x2,
+ 7);
processor.queuedRequests.add(writeReq4);
processor.queuedWriteRequests.add(writeReq4);
@@ -399,18 +391,14 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Processed unexpected committed request",
- !processor.committedRequests.isEmpty());
- Assert.assertTrue("Unexpected pending request",
- processor.pendingRequests.isEmpty());
- Assert.assertTrue("Removed from blockedQueuedRequests",
- !processor.queuedWriteRequests.isEmpty());
- Assert.assertTrue("Removed write req 4 from blockedQueuedRequests",
- processor.queuedWriteRequests.peek() == writeReq4);
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Processed unexpected committed request", !processor.committedRequests.isEmpty());
+ assertTrue("Unexpected pending request", processor.pendingRequests.isEmpty());
+ assertTrue("Removed from blockedQueuedRequests", !processor.queuedWriteRequests.isEmpty());
+ assertTrue(
+ "Removed write req 4 from blockedQueuedRequests",
+ processor.queuedWriteRequests.peek() == writeReq4);
processor.stoppedMainLoop = true;
CommitProcessor.setMaxCommitBatchSize(3);
@@ -418,16 +406,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Did not process committed request",
- processor.committedRequests.isEmpty());
- Assert.assertTrue("Did not process committed request",
- processor.pendingRequests.isEmpty());
- Assert.assertTrue("Did not remove from blockedQueuedRequests",
- processor.queuedWriteRequests.isEmpty());
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Did not process committed request", processor.committedRequests.isEmpty());
+ assertTrue("Did not process committed request", processor.pendingRequests.isEmpty());
+ assertTrue("Did not remove from blockedQueuedRequests", processor.queuedWriteRequests.isEmpty());
}
@@ -444,9 +427,10 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
Set<Request> nonLocalCommits = new HashSet<Request>();
for (int i = 0; i < 10; i++) {
Request nonLocalCommitReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 51, i + 1);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 51,
+ i + 1);
processor.committedRequests.add(nonLocalCommitReq);
nonLocalCommits.add(nonLocalCommitReq);
}
@@ -455,8 +439,7 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
}
- Assert.assertTrue("commit request was not processed",
- processedRequests.containsAll(nonLocalCommits));
+ assertTrue("commit request was not processed", processedRequests.containsAll(nonLocalCommits));
}
/**
@@ -474,42 +457,47 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
// +1 committed requests (also head of queuedRequests)
Request firstCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x3, 1);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x3,
+ 1);
processor.queuedRequests.add(firstCommittedReq);
processor.queuedWriteRequests.add(firstCommittedReq);
processor.committedRequests.add(firstCommittedReq);
Set<Request> allReads = new HashSet<Request>();
// +1 read request to queuedRequests
- Request firstRead = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, 0);
+ Request firstRead = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, 0);
allReads.add(firstRead);
processor.queuedRequests.add(firstRead);
// +1 non local commit
Request secondCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x99, 2);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x99,
+ 2);
processor.committedRequests.add(secondCommittedReq);
Set<Request> waitingCommittedRequests = new HashSet<Request>();
// +99 non local committed requests
for (int writeReqId = 3; writeReqId < 102; ++writeReqId) {
Request writeReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x8, writeReqId);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x8,
+ writeReqId);
processor.committedRequests.add(writeReq);
waitingCommittedRequests.add(writeReq);
}
// +50 read requests to queuedRequests
for (int readReqId = 1; readReqId <= 50; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x5, readReqId);
+ Request readReq = newRequest(
+ new GetDataRequest(path, false),
+ OpCode.getData,
+ 0x5,
+ readReqId);
allReads.add(readReq);
processor.queuedRequests.add(readReq);
}
@@ -518,20 +506,15 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
- Assert.assertTrue("Did not process the first write request",
- processedRequests.contains(firstCommittedReq));
+ assertTrue("Did not process the first write request", processedRequests.contains(firstCommittedReq));
for (Request r : allReads) {
- Assert.assertTrue("Processed read request",
- !processedRequests.contains(r));
+ assertTrue("Processed read request", !processedRequests.contains(r));
}
processor.run();
- Assert.assertTrue("did not processed all reads",
- processedRequests.containsAll(allReads));
- Assert.assertTrue("Did not process the second write request",
- processedRequests.contains(secondCommittedReq));
+ assertTrue("did not processed all reads", processedRequests.containsAll(allReads));
+ assertTrue("Did not process the second write request", processedRequests.contains(secondCommittedReq));
for (Request r : waitingCommittedRequests) {
- Assert.assertTrue("Processed additional committed request",
- !processedRequests.contains(r));
+ assertTrue("Processed additional committed request", !processedRequests.contains(r));
}
}
@@ -552,49 +535,50 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
HashSet<Request> localRequests = new HashSet<Request>();
// queue the blocking write request to queuedRequests
Request firstCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, readReqId++);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ readReqId++);
processor.queuedRequests.add(firstCommittedReq);
processor.queuedWriteRequests.add(firstCommittedReq);
localRequests.add(firstCommittedReq);
// queue read requests to queuedRequests
- for (; readReqId <= numberofReads+firstCXid; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionid, readReqId);
+ for (; readReqId <= numberofReads + firstCXid; ++readReqId) {
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionid, readReqId);
processor.queuedRequests.add(readReq);
localRequests.add(readReq);
}
//run once
- Assert.assertTrue(processor.queuedRequests.containsAll(localRequests));
+ assertTrue(processor.queuedRequests.containsAll(localRequests));
processor.initThreads(defaultSizeOfThreadPool);
processor.run();
Thread.sleep(1000);
//We verify that the processor is waiting for the commit
- Assert.assertTrue(processedRequests.isEmpty());
+ assertTrue(processedRequests.isEmpty());
// We add a commit that belongs to the same session but with smaller cxid,
// i.e., commit of an update from previous connection of this session.
Request preSessionCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, firstCXid - 2);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ firstCXid - 2);
processor.committedRequests.add(preSessionCommittedReq);
processor.committedRequests.add(firstCommittedReq);
processor.run();
Thread.sleep(1000);
//We verify that the commit processor processed the old commit prior to the newer messages
- Assert.assertTrue(processedRequests.peek() == preSessionCommittedReq);
+ assertTrue(processedRequests.peek() == preSessionCommittedReq);
processor.run();
Thread.sleep(1000);
//We verify that the commit processor handle all messages.
- Assert.assertTrue(processedRequests.containsAll(localRequests));
+ assertTrue(processedRequests.containsAll(localRequests));
}
/**
@@ -617,17 +601,17 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
// queue the blocking write request to queuedRequests
Request orphanCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, lastCXid);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ lastCXid);
processor.queuedRequests.add(orphanCommittedReq);
processor.queuedWriteRequests.add(orphanCommittedReq);
localRequests.add(orphanCommittedReq);
// queue read requests to queuedRequests
- for (; readReqId <= numberofReads+lastCXid; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionid, readReqId);
+ for (; readReqId <= numberofReads + lastCXid; ++readReqId) {
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionid, readReqId);
processor.queuedRequests.add(readReq);
localRequests.add(readReq);
}
@@ -638,27 +622,33 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
Thread.sleep(1000);
//We verify that the processor is waiting for the commit
- Assert.assertTrue(processedRequests.isEmpty());
+ assertTrue(processedRequests.isEmpty());
// We add a commit that belongs to the same session but with larger cxid,
// i.e., commit of an update from the next connection of this session.
Request otherSessionCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, lastCXid+10);
+ new CreateRequest(
+ path,
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ lastCXid + 10);
processor.committedRequests.add(otherSessionCommittedReq);
processor.committedRequests.add(orphanCommittedReq);
processor.run();
Thread.sleep(1000);
//We verify that the commit processor processed the old commit prior to the newer messages
- Assert.assertTrue(processedRequests.size() == 1);
- Assert.assertTrue(processedRequests.contains(otherSessionCommittedReq));
+ assertTrue(processedRequests.size() == 1);
+ assertTrue(processedRequests.contains(otherSessionCommittedReq));
processor.run();
Thread.sleep(1000);
//We verify that the commit processor handle all messages.
- Assert.assertTrue(processedRequests.containsAll(localRequests));
+ assertTrue(processedRequests.containsAll(localRequests));
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
index 2bef68843..29fe94b81 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,27 +18,30 @@
package org.apache.zookeeper.server.quorum;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.server.*;
+import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.server.RequestProcessor;
+import org.apache.zookeeper.server.ServerMetrics;
+import org.apache.zookeeper.server.WorkerService;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.nio.ByteBuffer;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.Matchers.*;
-
public class CommitProcessorMetricsTest extends ZKTestCase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(CommitProcessorMetricsTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(CommitProcessorMetricsTest.class);
CommitProcessor commitProcessor;
DummyFinalProcessor finalProcessor;
@@ -57,7 +60,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
System.clearProperty("zookeeper.commitProcessor.maxCommitBatchSize");
}
- public void setupProcessors(int commitWorkers, int finalProcTime ) {
+ public void setupProcessors(int commitWorkers, int finalProcTime) {
finalProcessor = new DummyFinalProcessor(finalProcTime);
commitProcessor = new TestCommitProcessor(finalProcessor, commitWorkers);
commitProcessor.start();
@@ -72,6 +75,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
}
private class TestCommitProcessor extends CommitProcessor {
+
int numWorkerThreads;
public TestCommitProcessor(RequestProcessor finalProcessor, int numWorkerThreads) {
@@ -101,7 +105,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
while (state != State.WAITING) {
try {
Thread.sleep(50);
- } catch (Exception e){
+ } catch (Exception e) {
}
state = super.getState();
@@ -126,9 +130,11 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
poolEmpytied.countDown();
}
}
+
}
private class TestWorkerService extends WorkerService {
+
public TestWorkerService(int numWorkerThreads) {
super("CommitProcWork", numWorkerThreads, true);
}
@@ -140,9 +146,11 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
requestScheduled.countDown();
}
}
+
}
private class DummyFinalProcessor implements RequestProcessor {
+
int processTime;
public DummyFinalProcessor(int processTime) {
this.processTime = processTime;
@@ -163,33 +171,32 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
}
@Override
- public void shutdown(){
+ public void shutdown() {
}
+
}
private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum) {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals("expected min is " + min, min, values.get("min_" + metricName));
- Assert.assertEquals("expected max is: " + max, max, values.get("max_" + metricName));
- Assert.assertEquals("expected avg is: " + avg, avg, (Double)values.get("avg_" + metricName), 0.001);
- Assert.assertEquals("expected cnt is: " + cnt, cnt, values.get("cnt_" + metricName));
- Assert.assertEquals("expected sum is: " + sum, sum, values.get("sum_" + metricName));
+ assertEquals("expected min is " + min, min, values.get("min_" + metricName));
+ assertEquals("expected max is: " + max, max, values.get("max_" + metricName));
+ assertEquals("expected avg is: " + avg, avg, (Double) values.get("avg_" + metricName), 0.001);
+ assertEquals("expected cnt is: " + cnt, cnt, values.get("cnt_" + metricName));
+ assertEquals("expected sum is: " + sum, sum, values.get("sum_" + metricName));
}
private void checkTimeMetric(long actual, long lBoundrary, long hBoundrary) {
- Assert.assertThat(actual, greaterThanOrEqualTo(lBoundrary));
- Assert.assertThat(actual, lessThanOrEqualTo(hBoundrary));
+ assertThat(actual, greaterThanOrEqualTo(lBoundrary));
+ assertThat(actual, lessThanOrEqualTo(hBoundrary));
}
private Request createReadRequest(long sessionId, int xid) {
- return new Request(null, sessionId, xid, ZooDefs.OpCode.getData,
- ByteBuffer.wrap(new byte[10]), null);
+ return new Request(null, sessionId, xid, ZooDefs.OpCode.getData, ByteBuffer.wrap(new byte[10]), null);
}
private Request createWriteRequest(long sessionId, int xid) {
- return new Request(null, sessionId, xid, ZooDefs.OpCode.setData,
- ByteBuffer.wrap(new byte[10]), null);
+ return new Request(null, sessionId, xid, ZooDefs.OpCode.setData, ByteBuffer.wrap(new byte[10]), null);
}
private void processRequestWithWait(Request request) throws Exception {
@@ -208,14 +215,14 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
public void testRequestsInSessionQueue() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
checkMetrics("requests_in_session_queue", 1L, 1L, 1D, 1L, 1L);
//these two read requests will be stuck in the session queue because there is write in front of them
processRequestWithWait(createReadRequest(1L, 2));
- processRequestWithWait(createReadRequest(1L,3));
+ processRequestWithWait(createReadRequest(1L, 3));
checkMetrics("requests_in_session_queue", 1L, 3L, 2D, 3L, 6);
@@ -228,18 +235,18 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
public void testWriteFinalProcTime() throws Exception {
setupProcessors(0, 1000);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
//no request sent to next processor yet
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(0L, values.get("cnt_write_final_proc_time_ms"));
+ assertEquals(0L, values.get("cnt_write_final_proc_time_ms"));
commitWithWait(req1);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_write_final_proc_time_ms"));
- checkTimeMetric((long)values.get("max_write_final_proc_time_ms"), 1000L, 2000L);
+ assertEquals(1L, values.get("cnt_write_final_proc_time_ms"));
+ checkTimeMetric((long) values.get("max_write_final_proc_time_ms"), 1000L, 2000L);
}
@Test
@@ -249,8 +256,8 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
processRequestWithWait(createReadRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_read_final_proc_time_ms"));
- checkTimeMetric((long)values.get("max_read_final_proc_time_ms"), 1000L, 2000L);
+ assertEquals(1L, values.get("cnt_read_final_proc_time_ms"));
+ checkTimeMetric((long) values.get("max_read_final_proc_time_ms"), 1000L, 2000L);
}
@Test
@@ -259,8 +266,8 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
processRequestWithWait(createReadRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_commit_process_time"));
- checkTimeMetric((long)values.get("max_commit_process_time"), 0L, 1000L);
+ assertEquals(1L, values.get("cnt_commit_process_time"));
+ checkTimeMetric((long) values.get("max_commit_process_time"), 0L, 1000L);
}
@Test
@@ -270,23 +277,23 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
commitWithWait(createWriteRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_server_write_committed_time_ms"));
- checkTimeMetric((long)values.get("max_server_write_committed_time_ms"), 0L, 1000L);
+ assertEquals(1L, values.get("cnt_server_write_committed_time_ms"));
+ checkTimeMetric((long) values.get("max_server_write_committed_time_ms"), 0L, 1000L);
}
@Test
public void testLocalWriteCommittedTime() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
commitWithWait(req1);
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_local_write_committed_time_ms"));
- checkTimeMetric((long)values.get("max_local_write_committed_time_ms"), 0l, 1000l);
+ assertEquals(1L, values.get("cnt_local_write_committed_time_ms"));
+ checkTimeMetric((long) values.get("max_local_write_committed_time_ms"), 0L, 1000L);
- Request req2 = createWriteRequest(1l, 2);
+ Request req2 = createWriteRequest(1L, 2);
processRequestWithWait(req2);
//the second write will be stuck in the session queue for at least one second
//but the LOCAL_WRITE_COMMITTED_TIME is from when the commit is received
@@ -295,24 +302,23 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
commitWithWait(req2);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("cnt_local_write_committed_time_ms"));
- checkTimeMetric((long)values.get("max_local_write_committed_time_ms"), 0L, 1000L);
+ assertEquals(2L, values.get("cnt_local_write_committed_time_ms"));
+ checkTimeMetric((long) values.get("max_local_write_committed_time_ms"), 0L, 1000L);
}
-
@Test
public void testWriteCommitProcTime() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
commitWithWait(req1);
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_write_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_write_commitproc_time_ms"), 0l, 1000l);
+ assertEquals(1L, values.get("cnt_write_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_write_commitproc_time_ms"), 0L, 1000L);
- Request req2 = createWriteRequest(1l, 2);
+ Request req2 = createWriteRequest(1L, 2);
processRequestWithWait(req2);
//the second write will be stuck in the session queue for at least one second
Thread.sleep(1000);
@@ -320,57 +326,54 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
commitWithWait(req2);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("cnt_write_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_write_commitproc_time_ms"), 1000L, 2000L);
+ assertEquals(2L, values.get("cnt_write_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_write_commitproc_time_ms"), 1000L, 2000L);
}
-
@Test
public void testReadCommitProcTime() throws Exception {
setupProcessors(0, 0);
- processRequestWithWait(createReadRequest(1l, 1));
+ processRequestWithWait(createReadRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_read_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_read_commitproc_time_ms"), 0l, 1000l);
+ assertEquals(1L, values.get("cnt_read_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_read_commitproc_time_ms"), 0L, 1000L);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
- processRequestWithWait(createReadRequest(1l, 3));
+ processRequestWithWait(createReadRequest(1L, 3));
//the second read will be stuck in the session queue for at least one second
Thread.sleep(1000);
commitWithWait(req1);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("cnt_read_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_read_commitproc_time_ms"), 1000L, 2000L);
+ assertEquals(2L, values.get("cnt_read_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_read_commitproc_time_ms"), 1000L, 2000L);
}
-
@Test
public void testTimeWaitingEmptyPoolInCommitProcessorRead() throws Exception {
setupProcessors(1, 1000);
//three read requests will be scheduled first
requestScheduled = new CountDownLatch(3);
- commitProcessor.processRequest(createReadRequest(0l, 2));
- commitProcessor.processRequest(createReadRequest(1l, 3));
- commitProcessor.processRequest(createReadRequest(2l, 4));
+ commitProcessor.processRequest(createReadRequest(0L, 2));
+ commitProcessor.processRequest(createReadRequest(1L, 3));
+ commitProcessor.processRequest(createReadRequest(2L, 4));
requestScheduled.await(5, TimeUnit.SECONDS);
//add a commit request to trigger waitForEmptyPool
poolEmpytied = new CountDownLatch(1);
- commitProcessor.commit(createWriteRequest(1l, 1));
+ commitProcessor.commit(createWriteRequest(1L, 1));
poolEmpytied.await(5, TimeUnit.SECONDS);
- long actual = (long)MetricsUtils.currentServerMetrics().get("max_time_waiting_empty_pool_in_commit_processor_read_ms");
+ long actual = (long) MetricsUtils.currentServerMetrics().get("max_time_waiting_empty_pool_in_commit_processor_read_ms");
//since each request takes 1000ms to process, so the waiting shouldn't be more than three times of that
checkTimeMetric(actual, 2500L, 3500L);
}
-
@Test
public void testConcurrentRequestProcessingInCommitProcessor() throws Exception {
setupProcessors(3, 1000);
@@ -378,102 +381,100 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
//three read requests will be processed in parallel
commitSeen = new CountDownLatch(1);
requestScheduled = new CountDownLatch(3);
- commitProcessor.processRequest(createReadRequest(1l, 2));
- commitProcessor.processRequest(createReadRequest(1l, 3));
- commitProcessor.processRequest(createReadRequest(1l, 4));
+ commitProcessor.processRequest(createReadRequest(1L, 2));
+ commitProcessor.processRequest(createReadRequest(1L, 3));
+ commitProcessor.processRequest(createReadRequest(1L, 4));
requestScheduled.await(5, TimeUnit.SECONDS);
//add a commit request to trigger waitForEmptyPool, which will record number of requests being proccessed
poolEmpytied = new CountDownLatch(1);
- commitProcessor.commit(createWriteRequest(1l, 1));
+ commitProcessor.commit(createWriteRequest(1L, 1));
poolEmpytied.await(5, TimeUnit.SECONDS);
//this will change after we upstream batch write in CommitProcessor
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(3L, values.get("max_concurrent_request_processing_in_commit_processor"));
+ assertEquals(3L, values.get("max_concurrent_request_processing_in_commit_processor"));
}
@Test
public void testReadsAfterWriteInSessionQueue() throws Exception {
setupProcessors(0, 0);
//this read request is before write
- processRequestWithWait(createReadRequest(1l, 1));
+ processRequestWithWait(createReadRequest(1L, 1));
//one write request
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
-
//three read requests after the write
- processRequestWithWait(createReadRequest(1l, 2));
- processRequestWithWait(createReadRequest(1l, 3));
- processRequestWithWait(createReadRequest(1l, 4));
+ processRequestWithWait(createReadRequest(1L, 2));
+ processRequestWithWait(createReadRequest(1L, 3));
+ processRequestWithWait(createReadRequest(1L, 4));
//commit the write
commitWithWait(req1);
- checkMetrics("reads_after_write_in_session_queue", 3l, 3l, 3d, 1, 3);
+ checkMetrics("reads_after_write_in_session_queue", 3L, 3L, 3d, 1, 3);
}
-
@Test
public void testReadsQueuedInCommitProcessor() throws Exception {
setupProcessors(0, 0);
- processRequestWithWait(createReadRequest(1l, 1));
- processRequestWithWait(createReadRequest(1l, 2));
+ processRequestWithWait(createReadRequest(1L, 1));
+ processRequestWithWait(createReadRequest(1L, 2));
//recorded reads in the queue are 1, 1
- checkMetrics("read_commit_proc_req_queued", 1l, 1l, 1d, 2, 2);
+ checkMetrics("read_commit_proc_req_queued", 1L, 1L, 1d, 2, 2);
}
@Test
public void testWritesQueuedInCommitProcessor() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
- Request req2 = createWriteRequest(1l, 2);
+ Request req2 = createWriteRequest(1L, 2);
processRequestWithWait(req2);
//since we haven't got any commit request, the write request stays in the queue
//recorded writes in the queue are 1, 2
- checkMetrics("write_commit_proc_req_queued", 1l, 2l, 1.5d, 2, 3);
+ checkMetrics("write_commit_proc_req_queued", 1L, 2L, 1.5d, 2, 3);
commitWithWait(req1);
//recording is done before commit request is processed, so writes in the queue are: 1, 2, 2
- checkMetrics("write_commit_proc_req_queued", 1l, 2l, 1.6667d, 3, 5);
+ checkMetrics("write_commit_proc_req_queued", 1L, 2L, 1.6667d, 3, 5);
commitWithWait(req2);
//writes in the queue are 1, 2, 2, 1
- checkMetrics("write_commit_proc_req_queued", 1l, 2l, 1.5d, 4, 6);
+ checkMetrics("write_commit_proc_req_queued", 1L, 2L, 1.5d, 4, 6);
//send a read request to trigger the recording, this time the write queue should be empty
//writes in the queue are 1, 2, 2, 1, 0
- processRequestWithWait(createReadRequest(1l, 1));
+ processRequestWithWait(createReadRequest(1L, 1));
- checkMetrics("write_commit_proc_req_queued", 0l, 2l, 1.2d, 5, 6);
+ checkMetrics("write_commit_proc_req_queued", 0L, 2L, 1.2d, 5, 6);
}
@Test
public void testCommitsQueuedInCommitProcessor() throws Exception {
setupProcessors(0, 0);
- commitWithWait(createWriteRequest(1l, 1));
- commitWithWait(createWriteRequest(1l, 2));
+ commitWithWait(createWriteRequest(1L, 1));
+ commitWithWait(createWriteRequest(1L, 2));
//recorded commits in the queue are 1, 1
- checkMetrics("commit_commit_proc_req_queued", 1l, 1l, 1d, 2, 2);
+ checkMetrics("commit_commit_proc_req_queued", 1L, 1L, 1d, 2, 2);
}
@Test
public void testCommitsQueued() throws Exception {
setupProcessors(0, 0);
- commitWithWait(createWriteRequest(1l, 1));
- commitWithWait(createWriteRequest(1l, 2));
+ commitWithWait(createWriteRequest(1L, 1));
+ commitWithWait(createWriteRequest(1L, 2));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2l, (long)values.get("request_commit_queued"));
+ assertEquals(2L, (long) values.get("request_commit_queued"));
}
@Test
@@ -481,25 +482,26 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
setupProcessors(0, 0);
//one write request for session 1
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
//two write requests for session 2
- Request req2 = createWriteRequest(2l, 2);
+ Request req2 = createWriteRequest(2L, 2);
processRequestWithWait(req2);
- Request req3 = createWriteRequest(2l, 3);
+ Request req3 = createWriteRequest(2L, 3);
processRequestWithWait(req3);
commitWithWait(req1);
//there are two sessions with pending requests
- checkMetrics("pending_session_queue_size", 2l, 2l, 2d, 1, 2);
+ checkMetrics("pending_session_queue_size", 2L, 2L, 2d, 1, 2);
commitWithWait(req2);
//there is on session with pending requests
- checkMetrics("pending_session_queue_size", 1l, 2l, 1.5d, 2, 3);
+ checkMetrics("pending_session_queue_size", 1L, 2L, 1.5d, 2, 3);
commitWithWait(req3);
//there is one session with pending requests
- checkMetrics("pending_session_queue_size", 1l, 2l, 1.333d, 3, 4);
+ checkMetrics("pending_session_queue_size", 1L, 2L, 1.333d, 3, 4);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
index c6ee230ac..ae439db08 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -28,7 +31,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
@@ -43,7 +45,6 @@ import org.apache.zookeeper.server.RequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -68,8 +69,8 @@ import org.slf4j.LoggerFactory;
* 4. No in-flight write requests while processing a read request.
*/
public class CommitProcessorTest extends ZKTestCase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(CommitProcessorTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(CommitProcessorTest.class);
// The amount of ms each test case should run
static final int TEST_RUN_TIME_IN_MS = 5000;
@@ -79,43 +80,40 @@ public class CommitProcessorTest extends ZKTestCase {
boolean stopped;
TestZooKeeperServer zks;
File tmpDir;
- ArrayList<TestClientThread> testClients =
- new ArrayList<TestClientThread>();
+ ArrayList<TestClientThread> testClients = new ArrayList<TestClientThread>();
CommitProcessor commitProcessor;
- public void setUp(int numCommitThreads, int numClientThreads, int writePercent)
- throws Exception {
+ public void setUp(int numCommitThreads, int numClientThreads, int writePercent) throws Exception {
stopped = false;
- System.setProperty(
- CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS,
- Integer.toString(numCommitThreads));
+ System.setProperty(CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS, Integer.toString(numCommitThreads));
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
zks = new TestZooKeeperServer(tmpDir, tmpDir, 4000);
zks.startup();
- for(int i=0; i<numClientThreads; ++i) {
+ for (int i = 0; i < numClientThreads; ++i) {
TestClientThread client = new TestClientThread(writePercent);
testClients.add(client);
client.start();
}
}
-
- public void setUp(int numCommitThreads, int numReadOnlyClientThreads, int mixWorkloadClientThreads, int writePercent)
- throws Exception {
+
+ public void setUp(
+ int numCommitThreads,
+ int numReadOnlyClientThreads,
+ int mixWorkloadClientThreads,
+ int writePercent) throws Exception {
stopped = false;
- System.setProperty(
- CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS,
- Integer.toString(numCommitThreads));
+ System.setProperty(CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS, Integer.toString(numCommitThreads));
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
zks = new TestZooKeeperServer(tmpDir, tmpDir, 4000);
zks.startup();
- for(int i=0; i<mixWorkloadClientThreads; ++i) {
+ for (int i = 0; i < mixWorkloadClientThreads; ++i) {
TestClientThread client = new TestClientThread(writePercent);
testClients.add(client);
client.start();
}
- for(int i=0; i<numReadOnlyClientThreads; ++i) {
+ for (int i = 0; i < numReadOnlyClientThreads; ++i) {
TestClientThread client = new TestClientThread(0);
testClients.add(client);
client.start();
@@ -128,13 +126,12 @@ public class CommitProcessorTest extends ZKTestCase {
stopped = true;
zks.shutdown();
- for(TestClientThread client : testClients) {
+ for (TestClientThread client : testClients) {
client.interrupt();
client.join();
}
if (tmpDir != null) {
- Assert.assertTrue("delete " + tmpDir.toString(),
- ClientBase.recursiveDelete(tmpDir));
+ assertTrue("delete " + tmpDir.toString(), ClientBase.recursiveDelete(tmpDir));
}
processedReadRequests.set(0);
processedWriteRequests.set(0);
@@ -143,6 +140,7 @@ public class CommitProcessorTest extends ZKTestCase {
}
private class TestClientThread extends Thread {
+
long sessionId;
int cxid;
int nodeId;
@@ -156,13 +154,13 @@ public class CommitProcessorTest extends ZKTestCase {
public void sendWriteRequest() throws Exception {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- CreateRequest createReq = new CreateRequest(
- "/session" + Long.toHexString(sessionId) + "-" + (++nodeId),
- new byte[0], Ids.OPEN_ACL_UNSAFE, 1);
+ CreateRequest createReq = new CreateRequest("/session"
+ + Long.toHexString(sessionId)
+ + "-"
+ + (++nodeId), new byte[0], Ids.OPEN_ACL_UNSAFE, 1);
createReq.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
- Request req = new Request(null, sessionId, ++cxid, OpCode.create,
- bb, new ArrayList<Id>());
+ Request req = new Request(null, sessionId, ++cxid, OpCode.create, bb, new ArrayList<Id>());
zks.getFirstProcessor().processRequest(req);
}
@@ -170,12 +168,13 @@ public class CommitProcessorTest extends ZKTestCase {
public void sendReadRequest() throws Exception {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- GetDataRequest getDataRequest = new GetDataRequest(
- "/session" + Long.toHexString(sessionId) + "-" + nodeId, false);
+ GetDataRequest getDataRequest = new GetDataRequest("/session"
+ + Long.toHexString(sessionId)
+ + "-"
+ + nodeId, false);
getDataRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
- Request req = new Request(null, sessionId, ++cxid, OpCode.getData,
- bb, new ArrayList<Id>());
+ Request req = new Request(null, sessionId, ++cxid, OpCode.getData, bb, new ArrayList<Id>());
zks.getFirstProcessor().processRequest(req);
}
@@ -183,7 +182,7 @@ public class CommitProcessorTest extends ZKTestCase {
Random rand = new Random(Thread.currentThread().getId());
try {
sendWriteRequest();
- while(!stopped) {
+ while (!stopped) {
if (rand.nextInt(100) < writePercent) {
sendWriteRequest();
} else {
@@ -195,6 +194,7 @@ public class CommitProcessorTest extends ZKTestCase {
LOG.error("Uncaught exception in test: ", e);
}
}
+
}
@Test
@@ -205,12 +205,12 @@ public class CommitProcessorTest extends ZKTestCase {
synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertFalse(fail);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
// processedWriteRequests.get() == numClients since each client performs one write at the beginning (creates a znode)
- Assert.assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
+ assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
}
-
+
@Test
public void testNoCommitWorkersMixedWorkload() throws Exception {
int numClients = 10;
@@ -219,10 +219,10 @@ public class CommitProcessorTest extends ZKTestCase {
synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
+ assertFalse(fail);
checkProcessedRequest();
}
-
+
@Test
public void testOneCommitWorkerReadOnlyWorkload() throws Exception {
int numClients = 10;
@@ -231,68 +231,67 @@ public class CommitProcessorTest extends ZKTestCase {
synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertFalse(fail);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
// processedWriteRequests.get() == numClients since each client performs one write at the beginning (creates a znode)
- Assert.assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
+ assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
}
@Test
public void testOneCommitWorkerMixedWorkload() throws Exception {
setUp(1, 10, 25);
LOG.info("testOneCommitWorkerMixedWorkload 25w/75r workload test");
- synchronized(this) {
+ synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
+ assertFalse(fail);
checkProcessedRequest();
}
-
-
+
@Test
public void testManyCommitWorkersReadOnly() throws Exception {
int numClients = 10;
LOG.info("testManyCommitWorkersReadOnly");
setUp(10, numClients, 0);
- synchronized(this) {
+ synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertFalse(fail);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
// processedWriteRequests.get() == numClients since each client performs one write at the beginning (creates a znode)
- Assert.assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
+ assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
}
-
+
@Test
public void testManyCommitWorkersMixedWorkload() throws Exception {
- setUp(16, 8 , 8, 25);
+ setUp(16, 8, 8, 25);
LOG.info("testManyCommitWorkersMixedWorkload 8X0w/100r + 8X25w/75r workload test");
- synchronized(this) {
+ synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
+ assertFalse(fail);
checkProcessedRequest();
}
private void checkProcessedRequest() {
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
- Assert.assertTrue("No write requests processed", processedWriteRequests.get() > 0);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertTrue("No write requests processed", processedWriteRequests.get() > 0);
}
volatile boolean fail = false;
- synchronized private void failTest(String reason) {
+ private synchronized void failTest(String reason) {
fail = true;
notifyAll();
- Assert.fail(reason);
+ fail(reason);
}
private class TestZooKeeperServer extends ZooKeeperServer {
- public TestZooKeeperServer(File snapDir, File logDir, int tickTime)
- throws IOException {
+
+ public TestZooKeeperServer(File snapDir, File logDir, int tickTime) throws IOException {
super(snapDir, logDir, tickTime);
}
- public PrepRequestProcessor getFirstProcessor(){
+ public PrepRequestProcessor getFirstProcessor() {
return (PrepRequestProcessor) firstProcessor;
}
@@ -303,24 +302,22 @@ public class CommitProcessorTest extends ZKTestCase {
RequestProcessor finalProcessor = new FinalRequestProcessor(zks);
// ValidateProcessor is set up in a similar fashion to ToBeApplied
// processor, so it can do pre/post validating of requests
- ValidateProcessor validateProcessor =
- new ValidateProcessor(finalProcessor);
+ ValidateProcessor validateProcessor = new ValidateProcessor(finalProcessor);
commitProcessor = new CommitProcessor(validateProcessor, "1", true, null);
validateProcessor.setCommitProcessor(commitProcessor);
commitProcessor.start();
- MockProposalRequestProcessor proposalProcessor =
- new MockProposalRequestProcessor(commitProcessor);
+ MockProposalRequestProcessor proposalProcessor = new MockProposalRequestProcessor(commitProcessor);
proposalProcessor.start();
firstProcessor = new PrepRequestProcessor(zks, proposalProcessor);
getFirstProcessor().start();
}
+
}
-
- private class MockProposalRequestProcessor extends Thread
- implements RequestProcessor {
+
+ private class MockProposalRequestProcessor extends Thread implements RequestProcessor {
+
private final CommitProcessor commitProcessor;
- private final LinkedBlockingQueue<Request> proposals =
- new LinkedBlockingQueue<Request>();
+ private final LinkedBlockingQueue<Request> proposals = new LinkedBlockingQueue<Request>();
public MockProposalRequestProcessor(CommitProcessor commitProcessor) {
this.commitProcessor = commitProcessor;
@@ -330,9 +327,9 @@ public class CommitProcessorTest extends ZKTestCase {
public void run() {
Random rand = new Random(Thread.currentThread().getId());
try {
- while(true) {
+ while (true) {
// If it is a read-only test, there will be no proposals..
- if (!proposals.isEmpty()){
+ if (!proposals.isEmpty()) {
Request request = proposals.take();
Thread.sleep(5 + rand.nextInt(95));
commitProcessor.commit(request);
@@ -344,8 +341,7 @@ public class CommitProcessorTest extends ZKTestCase {
}
@Override
- public void processRequest(Request request)
- throws RequestProcessorException {
+ public void processRequest(Request request) throws RequestProcessorException {
commitProcessor.processRequest(request);
if (request.getHdr() != null) {
// fake propose request
@@ -361,16 +357,16 @@ public class CommitProcessorTest extends ZKTestCase {
commitProcessor.shutdown();
}
}
+
}
-
private class ValidateProcessor implements RequestProcessor {
+
Random rand = new Random(Thread.currentThread().getId());
RequestProcessor nextProcessor;
CommitProcessor commitProcessor;
AtomicLong expectedZxid = new AtomicLong(1);
- ConcurrentHashMap<Long, AtomicInteger> cxidMap =
- new ConcurrentHashMap<Long, AtomicInteger>();
+ ConcurrentHashMap<Long, AtomicInteger> cxidMap = new ConcurrentHashMap<Long, AtomicInteger>();
AtomicInteger outstandingReadRequests = new AtomicInteger(0);
AtomicInteger outstandingWriteRequests = new AtomicInteger(0);
@@ -383,13 +379,12 @@ public class CommitProcessorTest extends ZKTestCase {
this.commitProcessor = commitProcessor;
}
-
@Override
- public void processRequest(Request request)
- throws RequestProcessorException {
- if (stopped)
+ public void processRequest(Request request) throws RequestProcessorException {
+ if (stopped) {
return;
- if (request.type == OpCode.closeSession){
+ }
+ if (request.type == OpCode.closeSession) {
LOG.debug("ValidateProcessor got closeSession request=" + request);
nextProcessor.processRequest(request);
return;
@@ -399,19 +394,20 @@ public class CommitProcessorTest extends ZKTestCase {
if (isWriteRequest) {
outstandingWriteRequests.incrementAndGet();
validateWriteRequestVariant(request);
- LOG.debug("Starting write request zxid=" + request.zxid);
+ LOG.debug("Starting write request zxid={}", request.zxid);
} else {
- LOG.debug("Starting read request cxid="
- + request.cxid + " for session 0x"
- + Long.toHexString(request.sessionId));
+ LOG.debug(
+ "Starting read request cxid={} for session 0x{}",
+ request.cxid,
+ Long.toHexString(request.sessionId));
outstandingReadRequests.incrementAndGet();
validateReadRequestVariant(request);
}
-
+
// Insert random delay to test thread race conditions
try {
Thread.sleep(5 + rand.nextInt(25));
- } catch(InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore
}
nextProcessor.processRequest(request);
@@ -422,13 +418,14 @@ public class CommitProcessorTest extends ZKTestCase {
*/
if (isWriteRequest) {
outstandingWriteRequests.decrementAndGet();
- LOG.debug("Done write request zxid=" + request.zxid);
+ LOG.debug("Done write request zxid={}", request.zxid);
processedWriteRequests.incrementAndGet();
} else {
outstandingReadRequests.decrementAndGet();
- LOG.debug("Done read request cxid="
- + request.cxid + " for session 0x"
- + Long.toHexString(request.sessionId));
+ LOG.debug(
+ "Done read request cxid={} for session 0x{}",
+ request.cxid,
+ Long.toHexString(request.sessionId));
processedReadRequests.incrementAndGet();
}
validateRequest(request);
@@ -438,20 +435,20 @@ public class CommitProcessorTest extends ZKTestCase {
* Validate that this is the only request in the pipeline
*/
private void validateWriteRequestVariant(Request request) {
- if (stopped)
+ if (stopped) {
return;
+ }
long zxid = request.getHdr().getZxid();
int readRequests = outstandingReadRequests.get();
if (readRequests != 0) {
failTest("There are " + readRequests + " outstanding"
- + " read requests while issuing a write request zxid="
- + zxid);
+ + " read requests while issuing a write request zxid=" + zxid);
}
int writeRequests = outstandingWriteRequests.get();
if (writeRequests > 1) {
failTest("There are " + writeRequests + " outstanding"
- + " write requests while issuing a write request zxid="
- + zxid + " (expected one)");
+ + " write requests while issuing a write request zxid=" + zxid
+ + " (expected one)");
}
}
@@ -463,9 +460,8 @@ public class CommitProcessorTest extends ZKTestCase {
int writeRequests = outstandingWriteRequests.get();
if (writeRequests != 0) {
failTest("There are " + writeRequests + " outstanding"
- + " write requests while issuing a read request cxid="
- + request.cxid + " for session 0x"
- + Long.toHexString(request.sessionId));
+ + " write requests while issuing a read request cxid=" + request.cxid
+ + " for session 0x" + Long.toHexString(request.sessionId));
}
}
@@ -478,8 +474,7 @@ public class CommitProcessorTest extends ZKTestCase {
if (request.getHdr() != null) {
long zxid = request.getHdr().getZxid();
if (!expectedZxid.compareAndSet(zxid, zxid + 1)) {
- failTest("Write request, expected_zxid="
- + expectedZxid.get() + "; req_zxid=" + zxid);
+ failTest("Write request, expected_zxid=" + expectedZxid.get() + "; req_zxid=" + zxid);
}
}
@@ -487,19 +482,18 @@ public class CommitProcessorTest extends ZKTestCase {
AtomicInteger sessionCxid = cxidMap.get(request.sessionId);
if (sessionCxid == null) {
sessionCxid = new AtomicInteger(request.cxid + 1);
- AtomicInteger existingSessionCxid =
- cxidMap.putIfAbsent(request.sessionId, sessionCxid);
+ AtomicInteger existingSessionCxid = cxidMap.putIfAbsent(request.sessionId, sessionCxid);
if (existingSessionCxid != null) {
- failTest("Race condition adding cxid=" + request.cxid
+ failTest("Race condition adding cxid="
+ + request.cxid
+ " for session 0x"
+ Long.toHexString(request.sessionId)
- + " with other_cxid=" + existingSessionCxid.get());
+ + " with other_cxid="
+ + existingSessionCxid.get());
}
} else {
- if (!sessionCxid.compareAndSet(
- request.cxid, request.cxid + 1)) {
- failTest("Expected_cxid=" + sessionCxid.get()
- + "; req_cxid=" + request.cxid);
+ if (!sessionCxid.compareAndSet(request.cxid, request.cxid + 1)) {
+ failTest("Expected_cxid=" + sessionCxid.get() + "; req_cxid=" + request.cxid);
}
}
}
@@ -509,9 +503,11 @@ public class CommitProcessorTest extends ZKTestCase {
LOG.info("shutdown validateReadRequestVariant");
cxidMap.clear();
expectedZxid = new AtomicLong(1);
- if (nextProcessor!=null){
+ if (nextProcessor != null) {
nextProcessor.shutdown();
}
}
+
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java
index aeb4e0fee..c092c6cd6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,11 +18,10 @@
package org.apache.zookeeper.server.quorum;
+import java.util.concurrent.LinkedBlockingQueue;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.RequestProcessor;
-import java.util.concurrent.LinkedBlockingQueue;
-
/**
* Allows the blocking of the request processor queue on a ZooKeeperServer.
*
@@ -74,4 +73,5 @@ public class DelayRequestProcessor implements RequestProcessor {
zooKeeperServer.commitProcessor.nextProcessor = delayRequestProcessor;
return delayRequestProcessor;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java
index 0c869a234..fa18bf0e2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,10 +18,12 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
@@ -30,7 +32,6 @@ import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.QuorumBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -38,16 +39,17 @@ import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class EagerACLFilterTest extends QuorumBase {
+
protected boolean checkEnabled;
protected ServerState serverState;
protected final CountDownLatch callComplete = new CountDownLatch(1);
protected boolean complete = false;
- protected final static String PARENT_PATH = "/foo";
- protected final static String CHILD_PATH = "/foo/bar";
- protected final static String AUTH_PROVIDER = "digest";
- protected final static byte[] AUTH = "hello".getBytes();
- protected final static byte[] AUTHB = "goodbye".getBytes();
- protected final static byte[] DATA = "Hint Water".getBytes();
+ protected static final String PARENT_PATH = "/foo";
+ protected static final String CHILD_PATH = "/foo/bar";
+ protected static final String AUTH_PROVIDER = "digest";
+ protected static final byte[] AUTH = "hello".getBytes();
+ protected static final byte[] AUTHB = "goodbye".getBytes();
+ protected static final byte[] DATA = "Hint Water".getBytes();
protected TestableZooKeeper zkClient;
protected TestableZooKeeper zkClientB;
protected QuorumPeer zkLeader;
@@ -55,14 +57,7 @@ public class EagerACLFilterTest extends QuorumBase {
@Parameterized.Parameters
public static Collection<Object[]> data() {
- return Arrays.asList(
- new Object[][] {
- {ServerState.LEADING, true},
- {ServerState.LEADING, false},
- {ServerState.FOLLOWING, true},
- {ServerState.FOLLOWING, false},
- {ServerState.OBSERVING, true},
- {ServerState.OBSERVING, false}});
+ return Arrays.asList(new Object[][]{{ServerState.LEADING, true}, {ServerState.LEADING, false}, {ServerState.FOLLOWING, true}, {ServerState.FOLLOWING, false}, {ServerState.OBSERVING, true}, {ServerState.OBSERVING, false}});
}
public EagerACLFilterTest(ServerState state, boolean checkEnabled) {
@@ -113,17 +108,11 @@ public class EagerACLFilterTest extends QuorumBase {
}
private void assertTransactionState(String condition, long lastxid) {
- String assertion =
- String.format(
- "Server State: %s Check Enabled: %s %s",
- serverState,
- checkEnabled,
- condition);
+ String assertion = String.format("Server State: %s Check Enabled: %s %s", serverState, checkEnabled, condition);
if (checkEnabled) {
- Assert.assertEquals(assertion, lastxid, zkLeader.getLastLoggedZxid());
- }
- else {
- Assert.assertNotSame(assertion, lastxid, zkLeader.getLastLoggedZxid());
+ assertEquals(assertion, lastxid, zkLeader.getLastLoggedZxid());
+ } else {
+ assertNotSame(assertion, lastxid, zkLeader.getLastLoggedZxid());
}
}
@@ -133,9 +122,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -143,9 +130,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -154,12 +139,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed create", lastxid);
}
@@ -170,12 +153,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed create2", lastxid);
}
@@ -185,9 +166,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zkClientB.delete(PARENT_PATH, -1);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -197,12 +176,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.delete(CHILD_PATH, -1);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed delete", lastxid);
}
@@ -219,12 +196,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.setData(PARENT_PATH, DATA, -1);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed setData", lastxid);
}
@@ -234,9 +209,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
zkClientB.setACL(PARENT_PATH, Ids.READ_ACL_UNSAFE, -1);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -245,12 +218,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.setACL(PARENT_PATH, Ids.READ_ACL_UNSAFE, -1);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed setACL", lastxid);
}
@@ -266,15 +237,14 @@ public class EagerACLFilterTest extends QuorumBase {
lastxid = zkLeader.getLastLoggedZxid();
try {
- zk.create("/acltest", new byte[0], Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
- Assert.fail("Should have received an invalid acl error");
- } catch (KeeperException.InvalidACLException e) {}
+ zk.create("/acltest", new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("Should have received an invalid acl error");
+ } catch (KeeperException.InvalidACLException e) {
+ }
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("zxid after invalid ACL", lastxid);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java
index 9546c25cc..749eb8047 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,18 +15,19 @@
* 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
+import javax.security.sasl.SaslException;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
@@ -38,12 +39,10 @@ import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
-import javax.security.sasl.SaslException;
-
public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
+
private static int SERVER_COUNT = 3;
private MainThread[] mt = new MainThread[SERVER_COUNT];
@@ -55,22 +54,20 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
@Test(timeout = 120000)
public void testEphemeralNodeDeletion() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
// start all the servers
for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new MockTestQPMain();
@@ -81,14 +78,13 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// ensure all servers started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
CountdownWatcher watch = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[1],
- ClientBase.CONNECTION_TIMEOUT, watch);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[1], ClientBase.CONNECTION_TIMEOUT, watch);
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
/**
@@ -99,14 +95,14 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// 1: create ephemeral node
String nodePath = "/e1";
- zk.create(nodePath, "1".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL, firstEphemeralNode);
- assertEquals("Current session and ephemeral owner should be same",
- zk.getSessionId(), firstEphemeralNode.getEphemeralOwner());
+ zk.create(nodePath, "1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, firstEphemeralNode);
+ assertEquals(
+ "Current session and ephemeral owner should be same",
+ zk.getSessionId(),
+ firstEphemeralNode.getEphemeralOwner());
// 2: inject network problem in one of the follower
- CustomQuorumPeer follower = (CustomQuorumPeer) getByServerState(mt,
- ServerState.FOLLOWING);
+ CustomQuorumPeer follower = (CustomQuorumPeer) getByServerState(mt, ServerState.FOLLOWING);
follower.setInjectError(true);
// 3: close the session so that ephemeral node is deleted
@@ -115,19 +111,18 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// remove the error
follower.setInjectError(false);
- Assert.assertTrue("Faulted Follower should have joined quorum by now",
- ClientBase.waitForServerUp(
- "127.0.0.1:" + follower.getClientPort(),
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "Faulted Follower should have joined quorum by now",
+ ClientBase.waitForServerUp("127.0.0.1:" + follower.getClientPort(), CONNECTION_TIMEOUT));
QuorumPeer leader = getByServerState(mt, ServerState.LEADING);
assertNotNull("Leader should not be null", leader);
- Assert.assertTrue("Leader must be running", ClientBase.waitForServerUp(
- "127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
+ assertTrue(
+ "Leader must be running",
+ ClientBase.waitForServerUp("127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
watch = new CountdownWatcher();
- zk = new ZooKeeper("127.0.0.1:" + leader.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, watch);
+ zk = new ZooKeeper("127.0.0.1:" + leader.getClientPort(), ClientBase.CONNECTION_TIMEOUT, watch);
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
Stat exists = zk.exists(nodePath, false);
@@ -135,8 +130,9 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
CountdownWatcher followerWatch = new CountdownWatcher();
ZooKeeper followerZK = new ZooKeeper(
- "127.0.0.1:" + follower.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, followerWatch);
+ "127.0.0.1:" + follower.getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ followerWatch);
followerWatch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
Stat nodeAtFollower = followerZK.exists(nodePath, false);
@@ -145,23 +141,21 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// Create the node with another session
Stat currentEphemeralNode = new Stat();
- zk.create(nodePath, "2".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL, currentEphemeralNode);
+ zk.create(nodePath, "2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, currentEphemeralNode);
// close the session and newly created ephemeral node should be deleted
zk.close();
-
+
SyncCallback cb = new SyncCallback();
followerZK.sync(nodePath, cb, null);
cb.sync.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
-
+
nodeAtFollower = followerZK.exists(nodePath, false);
// Problem 2: Before fix, after session close the ephemeral node
// was not getting deleted. But now after the fix after session close
// ephemeral node is getting deleted.
- assertNull("After session close ephemeral node must be deleted",
- nodeAtFollower);
+ assertNull("After session close ephemeral node must be deleted", nodeAtFollower);
followerZK.close();
}
@@ -188,6 +182,7 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
}
static class CustomQuorumPeer extends QuorumPeer {
+
private boolean injectError = false;
public CustomQuorumPeer() throws SaslException {
@@ -195,10 +190,8 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
}
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(logFactory,
- this, this.getZkDb())) {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
void readPacket(QuorumPacket pp) throws IOException {
@@ -211,9 +204,8 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
super.readPacket(pp);
if (injectError && pp.getType() == Leader.PROPOSAL) {
String type = LearnerHandler.packetToString(pp);
- throw new SocketTimeoutException(
- "Socket timeout while reading the packet for operation "
- + type);
+ throw new SocketTimeoutException("Socket timeout while reading the packet for operation "
+ + type);
}
}
@@ -227,18 +219,23 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
}
static class MockTestQPMain extends TestQPMain {
+
@Override
protected QuorumPeer getQuorumPeer() throws SaslException {
return new CustomQuorumPeer();
}
+
}
-
+
private static class SyncCallback implements AsyncCallback.VoidCallback {
+
private final CountDownLatch sync = new CountDownLatch(1);
-
+
@Override
public void processResult(int rc, String path, Object ctx) {
- sync.countDown();
+ sync.countDown();
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java
index 09adbc4d3..84e20311f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java
@@ -17,43 +17,39 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.fail;
import java.io.File;
-import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLEBackwardElectionRoundTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLELostMessageTest.class);
int count;
- Map<Long,QuorumServer> peers;
- File tmpdir[];
- int port[];
+ Map<Long, QuorumServer> peers;
+ File[] tmpdir;
+ int[] port;
- QuorumCnxManager cnxManagers[];
+ QuorumCnxManager[] cnxManagers;
@Before
public void setUp() throws Exception {
count = 3;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
tmpdir = new File[count];
port = new int[count];
cnxManagers = new QuorumCnxManager[count - 1];
@@ -61,8 +57,8 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
@After
public void tearDown() throws Exception {
- for(int i = 0; i < (count - 1); i++){
- if(cnxManagers[i] != null){
+ for (int i = 0; i < (count - 1); i++) {
+ if (cnxManagers[i] != null) {
cnxManagers[i].halt();
}
}
@@ -90,12 +86,9 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
@Test
public void testBackwardElectionRound() throws Exception {
LOG.info("TestLE: {}, {}", getTestName(), count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
int clientport = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(clientport),
- new InetSocketAddress(PortAssignment.unique())));
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress(clientport), new InetSocketAddress(PortAssignment.unique())));
tmpdir[i] = ClientBase.createTmpDir();
port[i] = clientport;
}
@@ -118,7 +111,7 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
cnxManagers[0] = mockPeer.createCnxnManager();
cnxManagers[0].listener.start();
- cnxManagers[0].toSend(0l, initialMsg0);
+ cnxManagers[0].toSend(0L, initialMsg0);
/*
* Start mock server 2
@@ -127,7 +120,7 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
cnxManagers[1] = mockPeer.createCnxnManager();
cnxManagers[1].listener.start();
- cnxManagers[1].toSend(0l, initialMsg1);
+ cnxManagers[1].toSend(0L, initialMsg1);
/*
* Run another instance of leader election.
@@ -139,13 +132,13 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
/*
* Send the same messages, this time should not make 0 the leader.
*/
- cnxManagers[0].toSend(0l, initialMsg0);
- cnxManagers[1].toSend(0l, initialMsg1);
+ cnxManagers[0].toSend(0L, initialMsg0);
+ cnxManagers[1].toSend(0L, initialMsg1);
thread.join(5000);
if (!thread.isAlive()) {
- Assert.fail("Should not have joined");
+ fail("Should not have joined");
}
}
@@ -153,4 +146,5 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
private ByteBuffer getMsg() {
return FLETestUtils.createMsg(ServerState.FOLLOWING.ordinal(), 0, 0, 1);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java
index ad2b180cd..5c6ffb5b7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,33 +18,30 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLELostMessageTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLELostMessageTest.class);
int count;
- HashMap<Long,QuorumServer> peers;
- File tmpdir[];
- int port[];
+ HashMap<Long, QuorumServer> peers;
+ File[] tmpdir;
+ int[] port;
QuorumCnxManager cnxManager;
@@ -52,7 +49,7 @@ public class FLELostMessageTest extends ZKTestCase {
public void setUp() throws Exception {
count = 3;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
tmpdir = new File[count];
port = new int[count];
}
@@ -65,12 +62,9 @@ public class FLELostMessageTest extends ZKTestCase {
@Test
public void testLostMessage() throws Exception {
LOG.info("TestLE: {}, {}", getTestName(), count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
int clientport = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(clientport),
- new InetSocketAddress(PortAssignment.unique())));
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress(clientport), new InetSocketAddress(PortAssignment.unique())));
tmpdir[i] = ClientBase.createTmpDir();
port[i] = clientport;
}
@@ -89,7 +83,7 @@ public class FLELostMessageTest extends ZKTestCase {
mockServer();
thread.join(5000);
if (thread.isAlive()) {
- Assert.fail("Threads didn't join");
+ fail("Threads didn't join");
}
}
@@ -98,8 +92,9 @@ public class FLELostMessageTest extends ZKTestCase {
cnxManager = peer.createCnxnManager();
cnxManager.listener.start();
- cnxManager.toSend(1l, FLETestUtils.createMsg(ServerState.LOOKING.ordinal(), 0, 0, 0));
+ cnxManager.toSend(1L, FLETestUtils.createMsg(ServerState.LOOKING.ordinal(), 0, 0, 0));
cnxManager.recvQueue.take();
cnxManager.toSend(1L, FLETestUtils.createMsg(ServerState.FOLLOWING.ordinal(), 1, 0, 0));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java
index d856b79a6..b1b666278 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,24 +15,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.FastLeaderElection.Notification;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.server.util.ZxidUtils;
import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.FLETest;
-import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,13 +43,11 @@ public class FLEOutOfElectionTest {
@Before
public void setUp() throws Exception {
File tmpdir = ClientBase.createTmpDir();
- Map<Long, QuorumServer> peers = new HashMap<Long,QuorumServer>();
- for(int i = 0; i < 5; i++) {
- peers.put(Long.valueOf(i), new QuorumServer(Long.valueOf(i),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ Map<Long, QuorumServer> peers = new HashMap<Long, QuorumServer>();
+ for (int i = 0; i < 5; i++) {
+ peers.put(Long.valueOf(i), new QuorumServer(Long.valueOf(i), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
}
- QuorumPeer peer = new QuorumPeer(peers, tmpdir, tmpdir,
- PortAssignment.unique(), 3, 3, 1000, 2, 2, 2);
+ QuorumPeer peer = new QuorumPeer(peers, tmpdir, tmpdir, PortAssignment.unique(), 3, 3, 1000, 2, 2, 2);
fle = new FastLeaderElection(peer, peer.createCnxnManager());
}
@@ -64,8 +59,7 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(0x1, 4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING));
votes.put(4L, new Vote(0x1, 4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LEADING));
- Assert.assertTrue(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
+ assertTrue(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
}
@Test
@@ -76,8 +70,7 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING));
votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LEADING));
- Assert.assertTrue(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
+ assertTrue(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
}
@Test
@@ -88,8 +81,7 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING));
votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LEADING));
- Assert.assertTrue(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)).hasAllQuorums());
+ assertTrue(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)).hasAllQuorums());
}
@Test
@@ -100,13 +92,12 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 3, 2, ServerState.LOOKING));
votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 3, 2, ServerState.LEADING));
- Assert.assertFalse(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LOOKING)).hasAllQuorums());
+ assertFalse(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LOOKING)).hasAllQuorums());
}
@Test
public void testOutofElection() {
- HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>();
+ HashMap<Long, Vote> outofelection = new HashMap<Long, Vote>();
outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING));
outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING));
@@ -122,15 +113,13 @@ public class FLEOutOfElectionTest {
n.state = vote.getState();
n.peerEpoch = vote.getPeerEpoch();
n.sid = 5L;
-
+
// Set the logical clock to 1 on fle instance of server 3.
fle.logicalclock.set(0x1);
- Assert.assertTrue("Quorum check failed",
- fle.getVoteTracker(outofelection, new Vote(n.version, n.leader,
- n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums());
+ assertTrue("Quorum check failed", fle.getVoteTracker(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums());
- Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection,
- n.leader, n.electionEpoch));
+ assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java
index a907abdb9..45ce2baea 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java
@@ -17,27 +17,24 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.nio.ByteBuffer;
-
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
-
+import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.junit.Assert;
-
-import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
public class FLETestUtils extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLETestUtils.class);
/*
- * Thread to run an instance of leader election for
+ * Thread to run an instance of leader election for
* a given quorum peer.
*/
static class LEThread extends Thread {
+
private int i;
private QuorumPeer peer;
@@ -56,7 +53,7 @@ public class FLETestUtils extends ZKTestCase {
v = peer.getElectionAlg().lookForLeader();
if (v == null) {
- Assert.fail("Thread " + i + " got a null vote");
+ fail("Thread " + i + " got a null vote");
}
/*
@@ -67,18 +64,19 @@ public class FLETestUtils extends ZKTestCase {
LOG.info("Finished election: {}, {}", i, v.getId());
- Assert.assertTrue("State is not leading.", peer.getPeerState() == ServerState.LEADING);
+ assertTrue("State is not leading.", peer.getPeerState() == ServerState.LEADING);
} catch (Exception e) {
e.printStackTrace();
}
LOG.info("Joining");
}
+
}
/*
* Creates a leader election notification message.
*/
- static ByteBuffer createMsg(int state, long leader, long zxid, long epoch){
+ static ByteBuffer createMsg(int state, long leader, long zxid, long epoch) {
return FastLeaderElection.buildMsg(state, leader, zxid, 1, epoch);
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java
index 4005dbeb8..5cd825947 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,8 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
@@ -25,14 +27,11 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.security.sasl.SaslException;
-
import org.apache.jute.OutputArchive;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.Op;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
@@ -45,8 +44,6 @@ import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.test.ClientBase;
-
-import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -76,9 +73,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
@@ -87,16 +83,14 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
mt = new MainThread[ENSEMBLE_SERVERS];
zk = new ZooKeeper[ENSEMBLE_SERVERS];
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new CustomizedQPMain();
}
};
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
QuorumPeerMainTest.waitForAll(zk, States.CONNECTED);
LOG.info("all servers started");
@@ -115,13 +109,13 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
@After
public void tearDown() throws Exception {
if (mt != null) {
- for (MainThread t: mt) {
+ for (MainThread t : mt) {
t.shutdown();
}
}
if (zk != null) {
- for (ZooKeeper z: zk) {
+ for (ZooKeeper z : zk) {
z.close();
}
}
@@ -134,8 +128,7 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
createEmptyNode(zk[followerA], path);
LOG.info("Hook to catch the 2nd sub create node txn in multi-op");
- CustomDataTree dt =
- (CustomDataTree) mt[followerA].main.quorumPeer.getZkDb().getDataTree();
+ CustomDataTree dt = (CustomDataTree) mt[followerA].main.quorumPeer.getZkDb().getDataTree();
final ZooKeeperServer zkServer = mt[followerA].main.quorumPeer.getActiveServer();
@@ -152,11 +145,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
LOG.info("Issue a multi op to create 2 nodes");
zk[followerA].multi(Arrays.asList(
- Op.create(node1, node1.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create(node2, node2.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT))
- );
+ Op.create(node1, node1.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create(node2, node2.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)));
LOG.info("Restart the server");
mt[followerA].shutdown();
@@ -166,7 +156,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
QuorumPeerMainTest.waitForOne(zk[followerA], States.CONNECTED);
LOG.info("Make sure the node consistent with leader");
- Assert.assertEquals(new String(zk[leaderId].getData(node2, null, null)),
+ assertEquals(
+ new String(zk[leaderId].getData(node2, null, null)),
new String(zk[followerA].getData(node2, null, null)));
}
@@ -198,8 +189,7 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
mt[followerA].start();
QuorumPeerMainTest.waitForOne(zk[followerA], States.CONNECTED);
- LOG.info("Check and make sure the pzxid of the parent is the same " +
- "on leader and follower A");
+ LOG.info("Check and make sure the pzxid of the parent is the same " + "on leader and follower A");
compareStat(parent, leaderId, followerA);
}
@@ -231,15 +221,13 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
mt[followerA].start();
QuorumPeerMainTest.waitForOne(zk[followerA], States.CONNECTED);
- LOG.info("Check and make sure the pzxid of the parent is the same " +
- "on leader and follower A");
+ LOG.info("Check and make sure the pzxid of the parent is the same " + "on leader and follower A");
compareStat(parent, leaderId, followerA);
}
private void addSerializeListener(int sid, String parent, String child) {
final ZooKeeper zkClient = zk[followerA];
- CustomDataTree dt =
- (CustomDataTree) mt[sid].main.quorumPeer.getZkDb().getDataTree();
+ CustomDataTree dt = (CustomDataTree) mt[sid].main.quorumPeer.getZkDb().getDataTree();
dt.addListener(parent, new NodeSerializeListener() {
@Override
public void nodeSerialized(String path) {
@@ -253,14 +241,14 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
});
}
- private void compareStat(String path, int sid, int compareWithSid) throws Exception{
+ private void compareStat(String path, int sid, int compareWithSid) throws Exception {
Stat stat1 = new Stat();
zk[sid].getData(path, null, stat1);
Stat stat2 = new Stat();
zk[compareWithSid].getData(path, null, stat2);
- Assert.assertEquals(stat1, stat2);
+ assertEquals(stat1, stat2);
}
@Test
@@ -284,7 +272,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
LOG.info("Create a global session");
ZooKeeper globalClient = new ZooKeeper(
"127.0.0.1:" + clientPorts[followerA],
- ClientBase.CONNECTION_TIMEOUT, this);
+ ClientBase.CONNECTION_TIMEOUT,
+ this);
QuorumPeerMainTest.waitForOne(globalClient, States.CONNECTED);
LOG.info("Restart followerA to load the data from disk");
@@ -296,40 +285,35 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
LOG.info("Make sure the global sessions are consistent with leader");
- Map<Long, Integer> globalSessionsOnLeader =
- mt[leaderId].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
+ Map<Long, Integer> globalSessionsOnLeader = mt[leaderId].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
if (mt[followerA].main.quorumPeer == null) {
LOG.info("quorumPeer is null");
}
if (mt[followerA].main.quorumPeer.getZkDb() == null) {
LOG.info("zkDb is null");
}
- Map<Long, Integer> globalSessionsOnFollowerA =
- mt[followerA].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
- LOG.info("sessions are {}, {}", globalSessionsOnLeader.keySet(),
- globalSessionsOnFollowerA.keySet());
- Assert.assertTrue(globalSessionsOnFollowerA.keySet().containsAll(
- globalSessionsOnLeader.keySet()));
+ Map<Long, Integer> globalSessionsOnFollowerA = mt[followerA].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
+ LOG.info("sessions are {}, {}", globalSessionsOnLeader.keySet(), globalSessionsOnFollowerA.keySet());
+ assertTrue(globalSessionsOnFollowerA.keySet().containsAll(globalSessionsOnLeader.keySet()));
}
private void createEmptyNode(ZooKeeper zk, String path) throws Exception {
zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
- static interface NodeCreateListener {
- public void process(String path);
+ interface NodeCreateListener {
+
+ void process(String path);
}
static class CustomDataTree extends DataTree {
- Map<String, NodeCreateListener> nodeCreateListeners =
- new HashMap<String, NodeCreateListener>();
- Map<String, NodeSerializeListener> listeners =
- new HashMap<String, NodeSerializeListener>();
+
+ Map<String, NodeCreateListener> nodeCreateListeners = new HashMap<String, NodeCreateListener>();
+ Map<String, NodeSerializeListener> listeners = new HashMap<String, NodeSerializeListener>();
@Override
- public void serializeNodeData(OutputArchive oa, String path,
- DataNode node) throws IOException {
+ public void serializeNodeData(OutputArchive oa, String path, DataNode node) throws IOException {
super.serializeNodeData(oa, path, node);
NodeSerializeListener listener = listeners.get(path);
if (listener != null) {
@@ -342,32 +326,42 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
}
@Override
- public void createNode(final String path, byte data[], List<ACL> acl,
- long ephemeralOwner, int parentCVersion, long zxid,
- long time, Stat outputStat)
- throws NoNodeException, NodeExistsException {
+ public void createNode(
+ final String path,
+ byte[] data,
+ List<ACL> acl,
+ long ephemeralOwner,
+ int parentCVersion,
+ long zxid,
+ long time,
+ Stat outputStat) throws NoNodeException, NodeExistsException {
NodeCreateListener listener = nodeCreateListeners.get(path);
if (listener != null) {
listener.process(path);
}
- super.createNode(path, data, acl, ephemeralOwner, parentCVersion,
- zxid, time, outputStat);
+ super.createNode(path, data, acl, ephemeralOwner, parentCVersion, zxid, time, outputStat);
}
public void addNodeCreateListener(String path, NodeCreateListener listener) {
nodeCreateListeners.put(path, listener);
}
+
}
- static interface NodeSerializeListener {
- public void nodeSerialized(String path);
+ interface NodeSerializeListener {
+
+ void nodeSerialized(String path);
+
}
- static interface CommitSessionListener {
- public void process(long sessionId);
+ interface CommitSessionListener {
+
+ void process(long sessionId);
+
}
static class CustomizedQPMain extends TestQPMain {
+
CommitSessionListener commitSessionListener;
public void setCommitSessionListener(CommitSessionListener listener) {
@@ -388,15 +382,15 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
}
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(
- logFactory, this, this.getZkDb()) {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb()) {
@Override
public void createSessionTracker() {
sessionTracker = new LearnerSessionTracker(
- this, getZKDatabase().getSessionWithTimeOuts(),
- this.tickTime, self.getId(),
+ this,
+ getZKDatabase().getSessionWithTimeOuts(),
+ this.tickTime,
+ self.getId(),
self.areLocalSessionsEnabled(),
getZooKeeperServerListener()) {
@@ -413,5 +407,7 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
}
};
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
index a6a5ec759..7ce583d58 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,16 +18,30 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.jute.OutputArchive;
import org.apache.jute.Record;
-import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
+import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
import org.apache.zookeeper.server.util.SerializeUtils;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.TxnHeader;
@@ -37,23 +51,8 @@ import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertNotEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class LeaderBeanTest {
+
private Leader leader;
private LeaderBean leaderBean;
private FileTxnSnapLog fileTxnSnapLog;
@@ -70,18 +69,14 @@ public class LeaderBeanTest {
Map<Long, QuorumServer> peersView = new HashMap<Long, QuorumServer>();
InetAddress clientIP = InetAddress.getLoopbackAddress();
- peersView.put(Long.valueOf(myId),
- new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
+ peersView.put(Long.valueOf(myId), new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
quorumVerifierMock = mock(QuorumVerifier.class);
when(quorumVerifierMock.getAllMembers()).thenReturn(peersView);
qp.setQuorumVerifier(quorumVerifierMock, false);
File tmpDir = ClientBase.createEmptyTestDir();
- fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"),
- new File(tmpDir, "data_txnlog"));
+ fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
ZKDatabase zkDb = new ZKDatabase(fileTxnSnapLog);
zks = new LeaderZooKeeperServer(fileTxnSnapLog, qp, zkDb);
@@ -211,4 +206,5 @@ public class LeaderBeanTest {
assertTrue(followerInfo.contains("5"));
assertEquals("5\n", leaderBean.nonVotingFollowerInfo());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java
index bf741f4ca..40ddfe6f3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,33 +18,38 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.*;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-
public class LeaderMetricsTest extends ZKTestCase {
+
CountDownLatch createdLatch;
int oldLoggingFeq;
private class MyWatcher implements Watcher {
+
@Override
- public void process(WatchedEvent e){
+ public void process(WatchedEvent e) {
createdLatch.countDown();
}
+
}
@Before
@@ -56,7 +61,7 @@ public class LeaderMetricsTest extends ZKTestCase {
public void teardown() {
Leader.setAckLoggingFrequency(oldLoggingFeq);
}
-
+
@Test
public void testLeaderMetrics() throws Exception {
// set the logging frequency to one so we log the ack latency for every ack
@@ -75,25 +80,26 @@ public class LeaderMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("proposal_count"));
+ assertEquals(2L, values.get("proposal_count"));
// Quorum ack latency is per txn
- Assert.assertEquals(2L, values.get("cnt_quorum_ack_latency"));
- Assert.assertThat((long)values.get("min_quorum_ack_latency"), greaterThan(0L));
+ assertEquals(2L, values.get("cnt_quorum_ack_latency"));
+ assertThat((long) values.get("min_quorum_ack_latency"), greaterThan(0L));
int numberOfAckServers = 0;
// ack latency is per server
- for (int sid = 1; sid<=3; sid++) {
+ for (int sid = 1; sid <= 3; sid++) {
String metricName = "min_" + sid + "_ack_latency";
if (values.get(metricName) != null) {
numberOfAckServers++;
- Assert.assertThat((long) values.get("min_" + sid + "_ack_latency"), greaterThanOrEqualTo(0L));
+ assertThat((long) values.get("min_" + sid + "_ack_latency"), greaterThanOrEqualTo(0L));
}
}
// at least two servers should have send ACKs
- Assert.assertThat(numberOfAckServers, greaterThanOrEqualTo(2));
+ assertThat(numberOfAckServers, greaterThanOrEqualTo(2));
zk.close();
util.shutdownAll();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
index 2548acad1..91292de77 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,21 +18,22 @@
package org.apache.zookeeper.server.quorum;
+import static org.apache.zookeeper.server.quorum.ZabUtils.createLeader;
+import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.net.InetSocketAddress;
+import java.util.Map;
+import java.util.Set;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.io.File;
-import java.net.InetSocketAddress;
-import java.util.Map;
-import java.util.Set;
-
-import static org.apache.zookeeper.server.quorum.ZabUtils.createLeader;
-import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
-
public class LeaderWithObserverTest {
QuorumPeer peer;
@@ -50,18 +51,14 @@ public class LeaderWithObserverTest {
observerId = peers.size();
leader = createLeader(tmpDir, peer);
peer.leader = leader;
- peers.put(observerId, new QuorumPeer.QuorumServer(
- observerId, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- QuorumPeer.LearnerType.OBSERVER));
+ peers.put(observerId, new QuorumPeer.QuorumServer(observerId, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), QuorumPeer.LearnerType.OBSERVER));
// these tests are serial, we can speed up InterruptedException
peer.tickTime = 1;
}
@After
- public void tearDown(){
+ public void tearDown() {
leader.shutdown("end of test");
tmpDir.delete();
}
@@ -71,8 +68,8 @@ public class LeaderWithObserverTest {
long lastAcceptedEpoch = 5;
peer.setAcceptedEpoch(5);
- Assert.assertEquals("Unexpected vote in connectingFollowers", 0, leader.connectingFollowers.size());
- Assert.assertTrue(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 0, leader.connectingFollowers.size());
+ assertTrue(leader.waitingForNewEpoch);
try {
// Leader asks for epoch (mocking Leader.lead behavior)
// First add to connectingFollowers
@@ -81,10 +78,9 @@ public class LeaderWithObserverTest {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
- Assert.assertEquals("Leader shouldn't set new epoch until quorum of participants is in connectingFollowers",
- lastAcceptedEpoch, peer.getAcceptedEpoch());
- Assert.assertTrue(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
+ assertEquals("Leader shouldn't set new epoch until quorum of participants is in connectingFollowers", lastAcceptedEpoch, peer.getAcceptedEpoch());
+ assertTrue(leader.waitingForNewEpoch);
try {
// Observer asks for epoch (mocking LearnerHandler behavior)
leader.getEpochToPropose(observerId, lastAcceptedEpoch);
@@ -92,21 +88,20 @@ public class LeaderWithObserverTest {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
- Assert.assertEquals("Leader shouldn't set new epoch after observer asks for epoch",
- lastAcceptedEpoch, peer.getAcceptedEpoch());
- Assert.assertTrue(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
+ assertEquals("Leader shouldn't set new epoch after observer asks for epoch", lastAcceptedEpoch, peer.getAcceptedEpoch());
+ assertTrue(leader.waitingForNewEpoch);
try {
// Now participant asks for epoch (mocking LearnerHandler behavior). Second add to connectingFollowers.
// Triggers verifier.containsQuorum = true
leader.getEpochToPropose(participantId, lastAcceptedEpoch);
} catch (Exception e) {
- Assert.fail("Timed out in getEpochToPropose");
+ fail("Timed out in getEpochToPropose");
}
- Assert.assertEquals("Unexpected vote in connectingFollowers", 2, leader.connectingFollowers.size());
- Assert.assertEquals("Leader should record next epoch", lastAcceptedEpoch + 1, peer.getAcceptedEpoch());
- Assert.assertFalse(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 2, leader.connectingFollowers.size());
+ assertEquals("Leader should record next epoch", lastAcceptedEpoch + 1, peer.getAcceptedEpoch());
+ assertFalse(leader.waitingForNewEpoch);
}
@Test
@@ -114,33 +109,33 @@ public class LeaderWithObserverTest {
// things needed for waitForEpochAck to run (usually in leader.lead(), but we're not running leader here)
leader.leaderStateSummary = new StateSummary(leader.self.getCurrentEpoch(), leader.zk.getLastProcessedZxid());
- Assert.assertEquals("Unexpected vote in electingFollowers", 0, leader.electingFollowers.size());
- Assert.assertFalse(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 0, leader.electingFollowers.size());
+ assertFalse(leader.electionFinished);
try {
// leader calls waitForEpochAck, first add to electingFollowers
leader.waitForEpochAck(peer.getId(), new StateSummary(0, 0));
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
- Assert.assertFalse(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
+ assertFalse(leader.electionFinished);
try {
// observer calls waitForEpochAck, should fail verifier.containsQuorum
leader.waitForEpochAck(observerId, new StateSummary(0, 0));
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
- Assert.assertFalse(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
+ assertFalse(leader.electionFinished);
try {
// second add to electingFollowers, verifier.containsQuorum=true, waitForEpochAck returns without exceptions
leader.waitForEpochAck(participantId, new StateSummary(0, 0));
- Assert.assertEquals("Unexpected vote in electingFollowers", 2, leader.electingFollowers.size());
- Assert.assertTrue(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 2, leader.electingFollowers.size());
+ assertTrue(leader.electionFinished);
} catch (Exception e) {
- Assert.fail("Timed out in waitForEpochAck");
+ fail("Timed out in waitForEpochAck");
}
}
@@ -153,33 +148,34 @@ public class LeaderWithObserverTest {
leader.newLeaderProposal.addQuorumVerifier(peer.getQuorumVerifier());
Set<Long> ackSet = leader.newLeaderProposal.qvAcksetPairs.get(0).getAckset();
- Assert.assertEquals("Unexpected vote in ackSet", 0, ackSet.size());
- Assert.assertFalse(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 0, ackSet.size());
+ assertFalse(leader.quorumFormed);
try {
// leader calls waitForNewLeaderAck, first add to ackSet
leader.waitForNewLeaderAck(peer.getId(), zxid);
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
- Assert.assertFalse(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
+ assertFalse(leader.quorumFormed);
try {
// observer calls waitForNewLeaderAck, should fail verifier.containsQuorum
leader.waitForNewLeaderAck(observerId, zxid);
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
- Assert.assertFalse(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
+ assertFalse(leader.quorumFormed);
try {
// second add to ackSet, verifier.containsQuorum=true, waitForNewLeaderAck returns without exceptions
leader.waitForNewLeaderAck(participantId, zxid);
- Assert.assertEquals("Unexpected vote in ackSet", 2, ackSet.size());
- Assert.assertTrue(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 2, ackSet.size());
+ assertTrue(leader.quorumFormed);
} catch (Exception e) {
- Assert.fail("Timed out in waitForEpochAck");
+ fail("Timed out in waitForEpochAck");
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java
index f3ebb6936..b6699d806 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,13 +18,14 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.server.ServerMetrics;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -32,23 +33,24 @@ import java.net.Socket;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.server.ServerMetrics;
+import org.junit.Before;
+import org.junit.Test;
public class LearnerHandlerMetricsTest {
+
private MockLearnerHandler learnerHandler;
private long sid = 5;
private volatile CountDownLatch allSentLatch = null;
class MockLearnerHandler extends LearnerHandler {
+
MockLearnerHandler(Socket socket, Leader leader) throws IOException {
super(socket, null, leader);
}
+
}
@Before
@@ -61,9 +63,10 @@ public class LearnerHandlerMetricsTest {
//adding 5ms artificial delay when sending each packet
BinaryOutputArchive oa = mock(BinaryOutputArchive.class);
- doAnswer(invocationOnMock -> {Thread.sleep(5); return null;})
- .when(oa).writeRecord(any(QuorumPacket.class), anyString());
-
+ doAnswer(invocationOnMock -> {
+ Thread.sleep(5);
+ return null;
+ }).when(oa).writeRecord(any(QuorumPacket.class), anyString());
BufferedOutputStream bos = mock(BufferedOutputStream.class);
// flush is called when all packets are sent and the queue is empty
@@ -85,7 +88,7 @@ public class LearnerHandlerMetricsTest {
ServerMetrics.getMetrics().resetAll();
//adding 1001 packets in the queue, two marker packets will be added since the interval is every 1000 packets
- for (int i=0; i<1001; i++) {
+ for (int i = 0; i < 1001; i++) {
learnerHandler.queuePacket(new QuorumPacket());
}
@@ -99,20 +102,21 @@ public class LearnerHandlerMetricsTest {
String sidStr = Long.toString(sid);
//we record time for each marker packet and we have two marker packets
- Assert.assertEquals(2L, values.get("cnt_" + sidStr + "_learner_handler_qp_time_ms"));
+ assertEquals(2L, values.get("cnt_" + sidStr + "_learner_handler_qp_time_ms"));
//the second marker has 1000 packets in front of it and each takes 5 ms to send so the time in queue should be
//longer than 5*1000
- Assert.assertThat((long)values.get("max_" + sidStr + "_learner_handler_qp_time_ms"), greaterThan(5000L));
+ assertThat((long) values.get("max_" + sidStr + "_learner_handler_qp_time_ms"), greaterThan(5000L));
//we send 1001 packets + 2 marker packets so the queue size is recorded 1003 times
- Assert.assertEquals(1003L, values.get("cnt_" + sidStr + "_learner_handler_qp_size"));
+ assertEquals(1003L, values.get("cnt_" + sidStr + "_learner_handler_qp_size"));
//the longest queue size is recorded when we are sending the first packet
- Assert.assertEquals(1002L, values.get("max_" + sidStr + "_learner_handler_qp_size"));
+ assertEquals(1002L, values.get("max_" + sidStr + "_learner_handler_qp_size"));
//this is when the queue is emptied
- Assert.assertEquals(0L, values.get("min_" + sidStr + "_learner_handler_qp_size"));
+ assertEquals(0L, values.get("min_" + sidStr + "_learner_handler_qp_size"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java
index f1dc7cc28..79b454a66 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -23,16 +23,15 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
+import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.TxnLogProposalIterator;
import org.apache.zookeeper.server.ZKDatabase;
@@ -48,10 +47,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LearnerHandlerTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(LearnerHandlerTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(LearnerHandlerTest.class);
class MockLearnerHandler extends LearnerHandler {
+
boolean threadStarted = false;
MockLearnerHandler(Socket sock, Leader leader) throws IOException {
@@ -66,9 +66,11 @@ public class LearnerHandlerTest extends ZKTestCase {
protected boolean shouldSendMarkerPacketForLogging() {
return false;
}
+
}
class MockZKDatabase extends ZKDatabase {
+
long lastProcessedZxid;
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
LinkedList<Proposal> committedLog = new LinkedList<Leader.Proposal>();
@@ -104,12 +106,11 @@ public class LearnerHandlerTest extends ZKTestCase {
return lock;
}
- public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid,
- long limit) {
+ public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid, long limit) {
if (peerZxid >= txnLog.peekFirst().packet.getZxid()) {
return txnLog.iterator();
} else {
- return (new LinkedList<Proposal>()).iterator();
+ return Collections.emptyIterator();
}
}
@@ -117,6 +118,7 @@ public class LearnerHandlerTest extends ZKTestCase {
public long calculateTxnLogSizeLimit() {
return 1;
}
+
}
private MockLearnerHandler learnerHandler;
@@ -136,9 +138,7 @@ public class LearnerHandlerTest extends ZKTestCase {
// Intercept when startForwarding is called
leader = mock(Leader.class);
- when(
- leader.startForwarding(ArgumentMatchers.any(LearnerHandler.class),
- ArgumentMatchers.anyLong())).thenAnswer(new Answer<Long>() {
+ when(leader.startForwarding(ArgumentMatchers.any(LearnerHandler.class), ArgumentMatchers.anyLong())).thenAnswer(new Answer<Long>() {
public Long answer(InvocationOnMock invocation) {
currentZxid = invocation.getArgument(1);
return 0L;
@@ -194,8 +194,10 @@ public class LearnerHandlerTest extends ZKTestCase {
}
void assertZxidEquals(long expected, long value) {
- assertEquals("Expected 0x" + Long.toHexString(expected) + " but was 0x"
- + Long.toHexString(value), expected, value);
+ assertEquals("Expected 0x"
+ + Long.toHexString(expected)
+ + " but was 0x"
+ + Long.toHexString(value), expected, value);
}
/**
@@ -258,18 +260,17 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, 3, 5);
// DIFF + 1 proposals + 1 commit
assertEquals(3, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5 });
+ queuedPacketMatches(new long[]{5});
reset();
// Peer is within committedLog range
peerZxid = 2;
assertFalse(learnerHandler.syncFollower(peerZxid, leader));
// We send DIFF and forward any packet starting lastProcessedZxid
- assertOpType(Leader.DIFF, db.getmaxCommittedLog(),
- db.getmaxCommittedLog());
+ assertOpType(Leader.DIFF, db.getmaxCommittedLog(), db.getmaxCommittedLog());
// DIFF + 2 proposals + 2 commit
assertEquals(5, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 3, 5 });
+ queuedPacketMatches(new long[]{3, 5});
reset();
// Peer miss the committedLog and txnlog is disabled
@@ -307,18 +308,17 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, 3, db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5, 6, 7, 8 });
+ queuedPacketMatches(new long[]{5, 6, 7, 8});
reset();
// Peer zxid is in txnlog range
peerZxid = 3;
assertFalse(learnerHandler.syncFollower(peerZxid, leader));
// We send DIFF and forward any packet starting at maxCommittedLog
- assertOpType(Leader.DIFF, db.getmaxCommittedLog(),
- db.getmaxCommittedLog());
+ assertOpType(Leader.DIFF, db.getmaxCommittedLog(), db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5, 6, 7, 8 });
+ queuedPacketMatches(new long[]{5, 6, 7, 8});
reset();
}
@@ -333,8 +333,7 @@ public class LearnerHandlerTest extends ZKTestCase {
// CommmitedLog is empty, we will use txnlog up to lastProcessZxid
db = new MockZKDatabase(null) {
@Override
- public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid,
- long limit) {
+ public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid, long limit) {
return TxnLogProposalIterator.EMPTY_ITERATOR;
}
};
@@ -345,8 +344,7 @@ public class LearnerHandlerTest extends ZKTestCase {
// Peer zxid
peerZxid = 4;
- assertTrue("Couldn't identify snapshot transfer!",
- learnerHandler.syncFollower(peerZxid, leader));
+ assertTrue("Couldn't identify snapshot transfer!", learnerHandler.syncFollower(peerZxid, leader));
reset();
}
@@ -374,7 +372,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, 3, db.lastProcessedZxid);
// DIFF + 3 proposals + 3 commit
assertEquals(7, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5, 6, 7 });
+ queuedPacketMatches(new long[]{5, 6, 7});
reset();
// Peer has zxid in txnlog range
@@ -384,7 +382,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.DIFF, db.lastProcessedZxid, db.lastProcessedZxid);
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 3, 5, 6, 7 });
+ queuedPacketMatches(new long[]{3, 5, 6, 7});
reset();
// Peer miss the txnlog
@@ -395,7 +393,7 @@ public class LearnerHandlerTest extends ZKTestCase {
reset();
}
- long getZxid(long epoch, long counter){
+ long getZxid(long epoch, long counter) {
return ZxidUtils.makeZxid(epoch, counter);
}
@@ -425,20 +423,17 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, getZxid(0xf, 3), db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(0xf, 5),
- getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8) });
+ queuedPacketMatches(new long[]{getZxid(0xf, 5), getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8)});
reset();
// Peer zxid is in txnlog range
peerZxid = getZxid(0xf, 3);
assertFalse(learnerHandler.syncFollower(peerZxid, leader));
// We send DIFF and forward any packet starting at maxCommittedLog
- assertOpType(Leader.DIFF, db.getmaxCommittedLog(),
- db.getmaxCommittedLog());
+ assertOpType(Leader.DIFF, db.getmaxCommittedLog(), db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(0xf, 5),
- getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8) });
+ queuedPacketMatches(new long[]{getZxid(0xf, 5), getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8)});
reset();
}
@@ -473,7 +468,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.DIFF, getZxid(1, 2), getZxid(1, 2));
// DIFF + 2 proposals + 2 commit
assertEquals(5, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(1, 1), getZxid(1, 2)});
+ queuedPacketMatches(new long[]{getZxid(1, 1), getZxid(1, 2)});
reset();
// Peer has zxid of epoch 2, so it is already sync
@@ -515,7 +510,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.DIFF, getZxid(1, 2), getZxid(1, 2));
// DIFF + 2 proposals + 2 commit
assertEquals(5, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(1, 1), getZxid(1, 2)});
+ queuedPacketMatches(new long[]{getZxid(1, 1), getZxid(1, 2)});
reset();
}
@@ -563,4 +558,5 @@ public class LearnerHandlerTest extends ZKTestCase {
assertTrue(learnerHandler.syncFollower(peerZxid, leader));
reset();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java
index b3df3ca53..b7b8c5aa4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,10 @@
package org.apache.zookeeper.server.quorum;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
@@ -29,12 +33,6 @@ import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Test;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-
public class LearnerMetricsTest extends QuorumPeerTestBase {
private static final int TIMEOUT_SECONDS = 30;
@@ -51,17 +49,17 @@ public class LearnerMetricsTest extends QuorumPeerTestBase {
final byte[] data = new byte[512];
final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
- int observer = 0 ;
+ int observer = 0;
clientPorts[observer] = PortAssignment.unique();
- sb.append("server."+observer+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+":observer\n");
- for(int i = 1; i < SERVER_COUNT; i++) {
+ sb.append("server." + observer + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":observer\n");
+ for (int i = 1; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- sb.append("server."+i+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+"\n");
+ sb.append("server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + "\n");
}
// start the participants
String quorumCfgSection = sb.toString();
- for(int i = 1; i < SERVER_COUNT; i++) {
+ for (int i = 1; i < SERVER_COUNT; i++) {
mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts[i], quorumCfgSection);
mt[i].start();
}
@@ -92,23 +90,22 @@ public class LearnerMetricsTest extends QuorumPeerTestBase {
private void waitForMetric(final String metricKey, final Matcher<Long> matcher) throws InterruptedException {
final String errorMessage = String.format("unable to match on metric: %s", metricKey);
- waitFor(errorMessage,
- () -> {
- long actual = (long) MetricsUtils.currentServerMetrics().get(metricKey);
- if(!matcher.matches(actual)) {
- LOG.info(String.format("match failed on %s, actual value: %d", metricKey, actual));
- return false;
- }
- return true;
- },
- TIMEOUT_SECONDS);
+ waitFor(errorMessage, () -> {
+ long actual = (long) MetricsUtils.currentServerMetrics().get(metricKey);
+ if (!matcher.matches(actual)) {
+ LOG.info(String.format("match failed on %s, actual value: %d", metricKey, actual));
+ return false;
+ }
+ return true;
+ }, TIMEOUT_SECONDS);
}
@After
public void tearDown() throws Exception {
zk_client.close();
- for(int i = 0; i < SERVER_COUNT; i++) {
+ for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java
index d3ce47b2d..9c6385e41 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -27,9 +30,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
-
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -38,22 +39,21 @@ import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public class LearnerSyncThrottlerTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(LearnerSyncThrottlerTest.class);
private LearnerSyncThrottler.SyncType syncType;
- public LearnerSyncThrottlerTest(LearnerSyncThrottler.SyncType syncType){
+ public LearnerSyncThrottlerTest(LearnerSyncThrottler.SyncType syncType) {
this.syncType = syncType;
}
@Parameterized.Parameters
public static Collection syncTypes() {
- return Arrays.asList(new Object[][]{
- {LearnerSyncThrottler.SyncType.DIFF}, {LearnerSyncThrottler.SyncType.SNAP}});
+ return Arrays.asList(new Object[][]{{LearnerSyncThrottler.SyncType.DIFF}, {LearnerSyncThrottler.SyncType.SNAP}});
}
@Test(expected = SyncThrottleException.class)
public void testTooManySyncsNonessential() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(5, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(5, syncType);
for (int i = 0; i < 6; i++) {
throttler.beginSync(false);
}
@@ -61,14 +61,13 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
@Test(expected = SyncThrottleException.class)
public void testTooManySyncsEssential() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(5, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(5, syncType);
try {
for (int i = 0; i < 6; i++) {
throttler.beginSync(true);
}
} catch (SyncThrottleException ex) {
- Assert.fail("essential syncs should not be throttled");
+ fail("essential syncs should not be throttled");
}
throttler.endSync();
throttler.beginSync(false);
@@ -76,32 +75,29 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
@Test
public void testNoThrottle() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(5, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(5, syncType);
try {
for (int i = 0; i < 6; i++) {
throttler.beginSync(true);
}
- }
- catch (SyncThrottleException ex) {
- Assert.fail("essential syncs should not be throttled");
+ } catch (SyncThrottleException ex) {
+ fail("essential syncs should not be throttled");
}
throttler.endSync();
for (int i = 0; i < 5; i++) {
throttler.endSync();
throttler.beginSync(false);
}
- Assert.assertTrue("should get here without exception", true);
+ assertTrue("should get here without exception", true);
}
@Test
public void testTryWithResourceNoThrottle() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(1, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(1, syncType);
for (int i = 0; i < 3; i++) {
throttler.beginSync(false);
try {
- Assert.assertEquals(1, throttler.getSyncInProgress());
+ assertEquals(1, throttler.getSyncInProgress());
} finally {
throttler.endSync();
}
@@ -110,18 +106,17 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
@Test
public void testTryWithResourceThrottle() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(1, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(1, syncType);
try {
throttler.beginSync(true);
try {
throttler.beginSync(false);
- Assert.fail("shouldn't be able to have both syncs open");
+ fail("shouldn't be able to have both syncs open");
} catch (SyncThrottleException e) {
}
throttler.endSync();
} catch (SyncThrottleException e) {
- Assert.fail("First sync shouldn't be throttled");
+ fail("First sync shouldn't be throttled");
}
}
@@ -129,8 +124,7 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
public void testParallelNoThrottle() {
final int numThreads = 50;
- final LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(numThreads, syncType);
+ final LearnerSyncThrottler throttler = new LearnerSyncThrottler(numThreads, syncType);
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
final CountDownLatch threadStartLatch = new CountDownLatch(numThreads);
final CountDownLatch syncProgressLatch = new CountDownLatch(numThreads);
@@ -162,12 +156,13 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
try {
for (Future<Boolean> result : results) {
- Assert.assertTrue(result.get());
+ assertTrue(result.get());
}
- } catch (Exception e){
+ } catch (Exception e) {
} finally {
threadPool.shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
index 7eccf6089..88647a22b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -27,7 +30,6 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.ZKTestCase;
@@ -38,19 +40,17 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.test.TestUtils;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Test;
public class LearnerTest extends ZKTestCase {
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
static class SimpleLearnerZooKeeperServer extends LearnerZooKeeperServer {
Learner learner;
- public SimpleLearnerZooKeeperServer(FileTxnSnapLog ftsl, QuorumPeer self)
- throws IOException {
+ public SimpleLearnerZooKeeperServer(FileTxnSnapLog ftsl, QuorumPeer self) throws IOException {
super(ftsl, 2000, 2000, 2000, -1, new ZKDatabase(ftsl), self);
}
@@ -58,17 +58,21 @@ public class LearnerTest extends ZKTestCase {
public Learner getLearner() {
return learner;
}
+
}
static class SimpleLearner extends Learner {
+
SimpleLearner(FileTxnSnapLog ftsl) throws IOException {
self = new QuorumPeer();
zk = new SimpleLearnerZooKeeperServer(ftsl, self);
((SimpleLearnerZooKeeperServer) zk).learner = this;
}
+
}
static class TimeoutLearner extends Learner {
+
int passSocketConnectOnAttempt = 10;
int socketConnectAttempt = 0;
long timeMultiplier = 0;
@@ -84,21 +88,21 @@ public class LearnerTest extends ZKTestCase {
protected long nanoTime() {
return socketConnectAttempt * timeMultiplier;
}
-
+
protected int getSockConnectAttempt() {
return socketConnectAttempt;
}
@Override
- protected void sockConnect(Socket sock, InetSocketAddress addr, int timeout)
- throws IOException {
- if (++socketConnectAttempt < passSocketConnectOnAttempt) {
+ protected void sockConnect(Socket sock, InetSocketAddress addr, int timeout) throws IOException {
+ if (++socketConnectAttempt < passSocketConnectOnAttempt) {
throw new IOException("Test injected Socket.connect() error.");
}
}
+
}
- @Test(expected=IOException.class)
+ @Test(expected = IOException.class)
public void connectionRetryTimeoutTest() throws Exception {
Learner learner = new TimeoutLearner();
learner.self = new QuorumPeer();
@@ -122,43 +126,43 @@ public class LearnerTest extends ZKTestCase {
// this addr won't even be used since we fake the Socket.connect
InetSocketAddress addr = new InetSocketAddress(1111);
-
+
// pretend each connect attempt takes 4000 milliseconds
- learner.setTimeMultiplier((long)4000 * 1000000);
-
+ learner.setTimeMultiplier((long) 4000 * 1000000);
+
learner.setPassConnectAttempt(5);
// we expect this to throw an IOException since we're faking socket connect errors every time
try {
learner.connectToLeader(addr, "");
- Assert.fail("should have thrown IOException!");
+ fail("should have thrown IOException!");
} catch (IOException e) {
//good, wanted to see that, let's make sure we ran out of time
- Assert.assertTrue(learner.nanoTime() > 2000*5*1000000);
- Assert.assertEquals(3, learner.getSockConnectAttempt());
+ assertTrue(learner.nanoTime() > 2000 * 5 * 1000000);
+ assertEquals(3, learner.getSockConnectAttempt());
}
}
@Test
public void connectToLearnerMasterLimitTest() throws Exception {
- TimeoutLearner learner = new TimeoutLearner();
- learner.self = new QuorumPeer();
- learner.self.setTickTime(2000);
- learner.self.setInitLimit(2);
- learner.self.setSyncLimit(2);
- learner.self.setConnectToLearnerMasterLimit(5);
-
- InetSocketAddress addr = new InetSocketAddress(1111);
- learner.setTimeMultiplier((long)4000 * 1000000);
- learner.setPassConnectAttempt(5);
-
- try {
- learner.connectToLeader(addr, "");
- Assert.fail("should have thrown IOException!");
- } catch (IOException e) {
- Assert.assertTrue(learner.nanoTime() > 2000*5*1000000);
- Assert.assertEquals(3, learner.getSockConnectAttempt());
- }
+ TimeoutLearner learner = new TimeoutLearner();
+ learner.self = new QuorumPeer();
+ learner.self.setTickTime(2000);
+ learner.self.setInitLimit(2);
+ learner.self.setSyncLimit(2);
+ learner.self.setConnectToLearnerMasterLimit(5);
+
+ InetSocketAddress addr = new InetSocketAddress(1111);
+ learner.setTimeMultiplier((long) 4000 * 1000000);
+ learner.setPassConnectAttempt(5);
+
+ try {
+ learner.connectToLeader(addr, "");
+ fail("should have thrown IOException!");
+ } catch (IOException e) {
+ assertTrue(learner.nanoTime() > 2000 * 5 * 1000000);
+ assertEquals(3, learner.getSockConnectAttempt());
+ }
}
@Test
@@ -199,13 +203,15 @@ public class LearnerTest extends ZKTestCase {
try {
sl.syncWithLeader(3);
- } catch (EOFException e) {}
+ } catch (EOFException e) {
+ }
sl.zk.shutdown();
sl = new SimpleLearner(ftsl);
- Assert.assertEquals(startZxid, sl.zk.getLastProcessedZxid());
+ assertEquals(startZxid, sl.zk.getLastProcessedZxid());
} finally {
TestUtils.deleteFileRecursively(tmpFile);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java
index 3554aac56..c15fd5b9e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,13 +19,12 @@
package org.apache.zookeeper.server.quorum;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.apache.zookeeper.PortAssignment;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java
index 650dc8286..0f9a8accb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,14 +18,14 @@
package org.apache.zookeeper.server.quorum;
-import org.junit.Test;
-
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import org.junit.Test;
public class QuorumBeanTest {
+
@Test
public void testGetNameProperty() {
QuorumPeer qpMock = mock(QuorumPeer.class);
@@ -72,4 +72,5 @@ public class QuorumBeanTest {
when(qpMock.shouldUsePortUnification()).thenReturn(false);
assertThat("isPortUnification property should return value of peer.shouldUsePortUnification()", qb.isPortUnification(), equalTo(false));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java
index 0bfb17dc5..0d7e7cce0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,26 +18,26 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Properties;
-
import org.apache.zookeeper.common.ClientX509Util;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.junit.Test;
-import static org.junit.Assert.*;
-
public class QuorumPeerConfigTest {
/**
* test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2264
*/
@Test
- public void testErrorMessageWhensecureClientPortNotSetButsecureClientPortAddressSet()
- throws IOException, ConfigException {
+ public void testErrorMessageWhensecureClientPortNotSetButsecureClientPortAddressSet() throws IOException, ConfigException {
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
try {
Properties zkProp = getDefaultZKProperties();
@@ -51,12 +51,11 @@ public class QuorumPeerConfigTest {
}
/**
- *
+ *
* Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2264
*/
@Test
- public void testErrorMessageWhenclientPortNotSetButclientPortAddressSet()
- throws IOException, ConfigException {
+ public void testErrorMessageWhenclientPortNotSetButclientPortAddressSet() throws IOException, ConfigException {
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
try {
Properties zkProp = getDefaultZKProperties();
@@ -73,8 +72,7 @@ public class QuorumPeerConfigTest {
* https://issues.apache.org/jira/browse/ZOOKEEPER-2297
*/
@Test
- public void testConfigureSSLAuthGetsConfiguredIfSecurePortConfigured()
- throws IOException, ConfigException {
+ public void testConfigureSSLAuthGetsConfiguredIfSecurePortConfigured() throws IOException, ConfigException {
String sslAuthProp = "zookeeper.authProvider.x509";
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
Properties zkProp = getDefaultZKProperties();
@@ -82,7 +80,7 @@ public class QuorumPeerConfigTest {
quorumPeerConfig.parseProperties(zkProp);
String expected = "org.apache.zookeeper.server.auth.X509AuthenticationProvider";
String result = System.getProperty(sslAuthProp);
- assertEquals(expected, result);
+ assertEquals(expected, result);
}
/**
@@ -119,17 +117,18 @@ public class QuorumPeerConfigTest {
* Extend the existing QuorumPeerConfig to set the server id.
*/
public static class MockQuorumPeerConfig extends QuorumPeerConfig {
+
public MockQuorumPeerConfig(long serverId) {
this.serverId = serverId;
}
+
}
/**
* Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2847
*/
@Test
- public void testClientAddrFromClientPort()
- throws IOException, ConfigException {
+ public void testClientAddrFromClientPort() throws IOException, ConfigException {
long serverId = 1;
QuorumPeerConfig quorumPeerConfig = new MockQuorumPeerConfig(serverId);
Properties zkProp = getDefaultZKProperties();
@@ -138,17 +137,14 @@ public class QuorumPeerConfigTest {
zkProp.setProperty("server.1", "127.0.0.1:2889:3889:participant");
quorumPeerConfig.parseProperties(zkProp);
- QuorumServer qs =
- quorumPeerConfig.getQuorumVerifier().getAllMembers().get(serverId);
- InetSocketAddress expectedAddress =
- new InetSocketAddress("0.0.0.0", clientPort);
+ QuorumServer qs = quorumPeerConfig.getQuorumVerifier().getAllMembers().get(serverId);
+ InetSocketAddress expectedAddress = new InetSocketAddress("0.0.0.0", clientPort);
assertEquals(expectedAddress, quorumPeerConfig.getClientPortAddress());
assertEquals(quorumPeerConfig.getClientPortAddress(), qs.clientAddr);
}
@Test
- public void testJvmPauseMonitorConfigured()
- throws IOException, ConfigException {
+ public void testJvmPauseMonitorConfigured() throws IOException, ConfigException {
final Long sleepTime = 444L;
final Long warnTH = 5555L;
final Long infoTH = 555L;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java
index a0bbc09de..a5cf9b8a9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -20,16 +20,22 @@ 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.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
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.IOException;
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;
@@ -40,7 +46,6 @@ 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;
@@ -50,9 +55,9 @@ 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.Ids;
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;
@@ -62,7 +67,6 @@ 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;
/**
@@ -80,63 +84,55 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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);
+ String server1 = String.format("server.1=%1$s:%2$s:%3$s;%4$s", addr, PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP1);
+ String server2 = String.format("server.2=%1$s:%2$s:%3$s;%4$s", addr, PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP2);
+
+ String quorumCfgSection = server1 + "\n" + server2;
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));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ 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(
+ assertEquals(
"Default value of minimumSessionTimeOut is not considered",
- tickTime * 2, quorumPeer.getMinSessionTimeout());
- Assert.assertEquals(
+ tickTime * 2,
+ quorumPeer.getMinSessionTimeout());
+ assertEquals(
"Default value of maximumSessionTimeOut is not considered",
- tickTime * 20, quorumPeer.getMaxSessionTimeout());
+ tickTime * 20,
+ quorumPeer.getMaxSessionTimeout());
- ZooKeeper zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT, this);
+ 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.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
zk.close();
- zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT, this);
+ 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.create("/foo_q2", "foobar2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -162,16 +158,16 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
public void testEarlyLeaderAbandonment() throws Exception {
ClientBase.setupTestEnv();
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ 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");
+ 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];
+ 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();
@@ -192,11 +188,10 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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;
@@ -211,15 +206,15 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
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) {}
+ zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ 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);
+ assertTrue(outstanding.size() == 1);
+ assertTrue(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();
@@ -244,9 +239,13 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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);
+ 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);
+ assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j))
+ + " does not have /zk"
+ + i, zk[j].exists("/zk" + i, false) != null);
}
}
}
@@ -271,7 +270,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
int leader = servers.findLeader();
// make sure there is a leader
- Assert.assertTrue("There should be a leader", leader >= 0);
+ assertTrue("There should be a leader", leader >= 0);
int nonleader = (leader + 1) % numServers;
@@ -322,9 +321,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 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);
+ 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
@@ -338,15 +335,11 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 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);
+ 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);
+ assertEquals("Validating that the deposed leader caught up on changes it missed", output[0], 2);
}
/**
@@ -372,68 +365,72 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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
- // and close the connection to the leader
- 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;
+ // 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();
+ assertTrue("There should be a leader", trueLeader >= 0);
+
+ // find a follower
+ int falseLeader = (trueLeader + 1) % numServers;
+ 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
+ // and close the connection to the leader
+ 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
+ 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);
+ 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);
+ assertTrue("falseLeader never attempts to become leader", foundLeading);
+ assertTrue("falseLeader never gives up on leadership", foundLooking);
+ assertTrue("falseLeader never rejoins the quorum", foundFollowing);
}
/**
@@ -453,26 +450,21 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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;
+ 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);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
- Assert.assertFalse("Server never came up", isup);
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -481,15 +473,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p =
- Pattern.compile(".*Cannot open channel to .* at election address .*");
+ Pattern p = Pattern.compile(".*Cannot open channel to .* at election address .*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about host", found);
+ assertTrue("complains about host", found);
}
/**
@@ -512,13 +503,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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;
+ 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);
@@ -527,29 +514,29 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 3 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP3, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -559,8 +546,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
String line;
boolean warningPresent = false;
boolean defaultedToObserver = false;
- Pattern pWarn =
- Pattern.compile(".*Peer type from servers list.* doesn't match peerType.*");
+ 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()) {
@@ -573,8 +559,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
break;
}
}
- Assert.assertTrue("Should warn about inconsistent peer type",
- warningPresent && defaultedToObserver);
+ assertTrue("Should warn about inconsistent peer type", warningPresent && defaultedToObserver);
}
/**
@@ -589,23 +574,20 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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;
+ 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));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ 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;
@@ -620,12 +602,10 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
s.write(buff);
s.close();
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT, this);
+ 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.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
zk.close();
q1.shutdown();
q2.shutdown();
@@ -650,33 +630,30 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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;
+ 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));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
zlogger.removeAppender(appender);
@@ -685,15 +662,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p =
- Pattern.compile(".*FastLeaderElection.*");
+ Pattern p = Pattern.compile(".*FastLeaderElection.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("fastleaderelection used", found);
+ assertTrue("fastleaderelection used", found);
}
/**
@@ -703,11 +679,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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();
+ 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
@@ -716,8 +689,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
q1.shutdown();
long end = Time.currentElapsedTime();
if ((end - start) > maxwait) {
- Assert.fail("QuorumPeer took " + (end - start) +
- " to shutdown, expected " + maxwait);
+ fail("QuorumPeer took " + (end - start) + " to shutdown, expected " + maxwait);
}
}
@@ -732,36 +704,30 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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();
+ 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";
+ + "minSessionTimeout=" + minSessionTimeOut + "\n";
- MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection,
- configs);
- MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection,
- configs);
+ 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));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ 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());
+ assertEquals("minimumSessionTimeOut is not considered", minSessionTimeOut, quorumPeer.getMinSessionTimeout());
+ assertEquals("maximumSessionTimeOut is not considered", maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
}
/**
@@ -775,35 +741,29 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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();
+ 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);
+ 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));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ 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());
+ assertEquals("minimumSessionTimeOut is not considered", minSessionTimeOut, quorumPeer.getMinSessionTimeout());
+ assertEquals("maximumSessionTimeOut is wrong", maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
}
@Test
@@ -825,7 +785,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 2. kill all followers
int leader = servers.findLeader();
- Map<Long, Proposal> outstanding = servers.mt[leader].main.quorumPeer.leader.outstandingProposals;
+ 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;
@@ -858,27 +818,25 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 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");
+ servers.zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ 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);
+ 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);
+ 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);
+ fail("Transaction not synced to disk within 1 second " + p.qvAcksetPairs.get(0).getAckset() + " expected " + leader);
}
Thread.sleep(100);
sleepTime += 100;
@@ -890,7 +848,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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());
+ fail("Took too long for old leader to time out "
+ + servers.mt[leader].main.quorumPeer.getPeerState());
}
Thread.sleep(100);
sleepTime += 100;
@@ -899,7 +858,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
int newLeader = servers.findLeader();
// make sure a different leader was elected
- Assert.assertNotEquals(leader, newLeader);
+ 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();
@@ -911,7 +870,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 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));
+ assertNull(
+ "server " + i + " should not have /zk" + leader,
+ servers.zk[i].exists("/zk" + leader, false));
}
}
@@ -954,13 +915,13 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 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);
+ 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);
+ assertTrue(quorumPeer3.getPeerState() == QuorumPeer.ServerState.LOOKING);
// Node 2 started last, kicks off leader election
for (int i = 1; i < highestServerIndex; i++) {
@@ -969,14 +930,16 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 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));
+ 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);
+ assertTrue(svrs.mt[0].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.LOOKING);
+ 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);
+ assertTrue(svrs.mt[i].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.FOLLOWING);
}
// Look through the logs for output that indicates Node 1 is LEADING or FOLLOWING
@@ -994,8 +957,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
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);
+ assertFalse("Corrupt peer should never become leader", foundLeading);
+ assertFalse("Corrupt peer should not attempt connection to out of view leader", foundFollowing);
}
@Test
@@ -1008,8 +971,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
QuorumPeerConfig configMock = mock(QuorumPeerConfig.class);
when(configMock.getDataDir()).thenReturn(dataDir);
when(configMock.getDataLogDir()).thenReturn(dataLogDir);
- when(configMock.getMetricsProviderClassName())
- .thenReturn(NullMetricsProvider.class.getName());
+ when(configMock.getMetricsProviderClassName()).thenReturn(NullMetricsProvider.class.getName());
QuorumPeer qpMock = mock(QuorumPeer.class);
@@ -1022,8 +984,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// Assert
FileTxnSnapLog txnFactory = qpMain.getQuorumPeer().getTxnFactory();
- Assert.assertEquals(Paths.get(dataLogDir.getAbsolutePath(), "version-2").toString(), txnFactory.getDataDir().getAbsolutePath());
- Assert.assertEquals(Paths.get(dataDir.getAbsolutePath(), "version-2").toString(), txnFactory.getSnapDir().getAbsolutePath());
+ assertEquals(Paths.get(dataLogDir.getAbsolutePath(), "version-2").toString(), txnFactory.getDataDir().getAbsolutePath());
+ assertEquals(Paths.get(dataDir.getAbsolutePath(), "version-2").toString(), txnFactory.getSnapDir().getAbsolutePath());
} finally {
FileUtils.deleteDirectory(dataDir);
FileUtils.deleteDirectory(dataLogDir);
@@ -1031,6 +993,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
private class InjectableQuorumPeerMain extends QuorumPeerMain {
+
QuorumPeer qp;
InjectableQuorumPeerMain(QuorumPeer qp) {
@@ -1041,6 +1004,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
protected QuorumPeer getQuorumPeer() {
return qp;
}
+
}
private WriterAppender getConsoleAppender(ByteArrayOutputStream os, Level level) {
@@ -1109,36 +1073,33 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 1. set up an ensemble with 3 servers
final int ENSEMBLE_SERVERS = 3;
- final int clientPorts[] = new int[ENSEMBLE_SERVERS];
+ final int[] clientPorts = new int[ENSEMBLE_SERVERS];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
// start servers
MainThread[] mt = new MainThread[ENSEMBLE_SERVERS];
- ZooKeeper zk[] = new ZooKeeper[ENSEMBLE_SERVERS];
- Context contexts[] = new Context[ENSEMBLE_SERVERS];
+ ZooKeeper[] zk = new ZooKeeper[ENSEMBLE_SERVERS];
+ Context[] contexts = new Context[ENSEMBLE_SERVERS];
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
final Context context = new Context();
contexts[i] = context;
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new CustomizedQPMain(context);
}
};
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
waitForAll(zk, States.CONNECTED);
LOG.info("all servers started");
@@ -1166,19 +1127,16 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 3. create a node
String initialValue = "1";
final ZooKeeper leaderZk = zk[leaderId];
- leaderZk.create(nodePath, initialValue.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ leaderZk.create(nodePath, initialValue.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("created node {} with value {}", nodePath, initialValue);
- CustomQuorumPeer leaderQuorumPeer =
- (CustomQuorumPeer) mt[leaderId].main.quorumPeer;
+ CustomQuorumPeer leaderQuorumPeer = (CustomQuorumPeer) mt[leaderId].main.quorumPeer;
// 4. on the customized leader catch the startForwarding call
// (without synchronized), set the node to value v1, then
// call the super.startForwarding to generate the ongoing
// txn proposal and commit for v1 value update
- leaderQuorumPeer.setStartForwardingListener(
- new StartForwardingListener() {
+ leaderQuorumPeer.setStartForwardingListener(new StartForwardingListener() {
@Override
public void start() {
if (!Boolean.getBoolean(LearnerHandler.FORCE_SNAP_SYNC)) {
@@ -1189,10 +1147,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// use async, otherwise it will block the logLock in
// ZKDatabase and the setData request will timeout
try {
- leaderZk.setData(nodePath, value.getBytes(), -1,
- new AsyncCallback.StatCallback() {
- public void processResult(int rc, String path,
- Object ctx, Stat stat) {}
+ leaderZk.setData(nodePath, value.getBytes(), -1, new AsyncCallback.StatCallback() {
+ public void processResult(int rc, String path, Object ctx, Stat stat) {
+ }
}, null);
// wait for the setData txn being populated
Thread.sleep(1000);
@@ -1209,8 +1166,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
public void start() {
String value = "3";
- LOG.info("before sending snapshot, set {} to {}",
- nodePath, value);
+ LOG.info("before sending snapshot, set {} to {}", nodePath, value);
try {
leaderZk.setData(nodePath, value.getBytes(), -1);
LOG.info("successfully set {} to {}", nodePath, value);
@@ -1221,8 +1177,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
});
// 6. exit follower A after taking snapshot
- CustomQuorumPeer followerAQuorumPeer =
- ((CustomQuorumPeer) mt[followerA].main.quorumPeer);
+ CustomQuorumPeer followerAQuorumPeer = ((CustomQuorumPeer) mt[followerA].main.quorumPeer);
LOG.info("set exit when ack new leader packet on {}", followerA);
contexts[followerA].exitWhenAckNewLeader = true;
CountDownLatch latch = new CountDownLatch(1);
@@ -1233,14 +1188,15 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
latch.countDown();
followerAMT.shutdown();
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
};
// 7. start follower A to do snapshot sync
LOG.info("starting follower {}", followerA);
mt[followerA].start();
- Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
+ assertTrue(latch.await(30, TimeUnit.SECONDS));
// 8. now we have invalid data on disk, let's load it and verify
LOG.info("disable exit when ack new leader packet on {}", followerA);
@@ -1252,16 +1208,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
mt[followerA].start();
zk[followerA].close();
- zk[followerA] = new ZooKeeper("127.0.0.1:" + clientPorts[followerA],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[followerA] = new ZooKeeper("127.0.0.1:" + clientPorts[followerA], ClientBase.CONNECTION_TIMEOUT, this);
// 9. start follower A, after it's in broadcast state, make sure
// the node value is same as what we have on leader
waitForOne(zk[followerA], States.CONNECTED);
- Assert.assertEquals(
+ assertEquals(
new String(zk[followerA].getData(nodePath, null, null)),
- new String(zk[leaderId].getData(nodePath, null, null))
- );
+ new String(zk[leaderId].getData(nodePath, null, null)));
} finally {
System.clearProperty(LearnerHandler.FORCE_SNAP_SYNC);
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
@@ -1290,28 +1244,24 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
* 2s to confirm this.
*/
@Test
- public void testLeaderElectionWithDisloyalVoter_stillHasMajority()
- throws IOException {
+ public void testLeaderElectionWithDisloyalVoter_stillHasMajority() throws IOException {
testLeaderElection(5, 5, 3000, 20000);
}
- void testLeaderElection(int totalServers, int serversToStart,
- int maxTimeToWaitForEpoch, int maxTimeWaitForServerUp)
- throws IOException {
+ void testLeaderElection(int totalServers, int serversToStart, int maxTimeToWaitForEpoch, int maxTimeWaitForServerUp) throws IOException {
Leader.setMaxTimeToWaitForEpoch(maxTimeToWaitForEpoch);
// set up config for an ensemble with given number of servers
servers = new Servers();
int ENSEMBLE_SERVERS = totalServers;
- final int clientPorts[] = new int[ENSEMBLE_SERVERS];
+ final int[] clientPorts = new int[ENSEMBLE_SERVERS];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
@@ -1330,8 +1280,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
context.quitFollowing = true;
}
contexts[i] = context;
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new CustomizedQPMain(context);
@@ -1343,10 +1292,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// make sure the quorum can be formed within initLimit * tickTime
// the default setting is 10 * 4000 = 40000 ms
for (int i = 0; i < SERVERS_TO_START; i++) {
- Assert.assertTrue(
+ assertTrue(
"Server " + i + " should have joined quorum by now",
- ClientBase.waitForServerUp(
- "127.0.0.1:" + clientPorts[i], maxTimeWaitForServerUp));
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], maxTimeWaitForServerUp));
}
}
@@ -1368,53 +1316,41 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSectionServer
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
+ String quorumCfgSectionServer = "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 + "\n";
// server 1 boots with a MetricsProvider
- String quorumCfgSectionServer1 =
- quorumCfgSectionServer
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.class.getName() + "\n";
+ String quorumCfgSectionServer1 = quorumCfgSectionServer
+ + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.class.getName() + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
q1.start();
q2.start();
- boolean isup1
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
- boolean isup2
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- 30000);
- Assert.assertTrue("Server 1 never came up", isup1);
- Assert.assertTrue("Server 2 never came up", isup2);
+ boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
+ boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
+ assertTrue("Server 1 never came up", isup1);
+ assertTrue("Server 2 never came up", isup2);
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ 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));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
}
/**
@@ -1435,48 +1371,40 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSectionServer
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
+ String quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
+ + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
// server 1 boots with a MetricsProvider
- String quorumCfgSectionServer1 =
- quorumCfgSectionServer
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithConfiguration.class.getName() + "\n"
- + "metricsProvider.httpPort=1234";
+ String quorumCfgSectionServer1 = quorumCfgSectionServer
+ + "metricsProvider.className="
+ + BaseTestMetricsProvider.MetricsProviderWithConfiguration.class.getName()
+ + "\n" + "metricsProvider.httpPort=1234";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
q1.start();
q2.start();
- boolean isup1
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
- boolean isup2
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- 30000);
- Assert.assertTrue("Server 1 never came up", isup1);
- Assert.assertTrue("Server 2 never came up", isup2);
+ boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
+ boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
+ assertTrue("Server 1 never came up", isup1);
+ assertTrue("Server 2 never came up", isup2);
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ 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));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
- Assert.assertEquals(1234,
- BaseTestMetricsProvider.MetricsProviderWithConfiguration.httpPort.get());
+ assertEquals(1234, BaseTestMetricsProvider.MetricsProviderWithConfiguration.httpPort.get());
}
/**
@@ -1497,60 +1425,52 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSectionServer
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
+ String quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
+ + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
// server 1 boots with a MetricsProvider
- String quorumCfgSectionServer1 =
- quorumCfgSectionServer
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInStop.class.getName() + "\n";
+ String quorumCfgSectionServer1 = quorumCfgSectionServer
+ + "metricsProvider.className="
+ + BaseTestMetricsProvider.MetricsProviderWithErrorInStop.class.getName()
+ + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
q1.start();
q2.start();
- boolean isup1
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
- boolean isup2
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- 30000);
- Assert.assertTrue("Server 1 never came up", isup1);
- Assert.assertTrue("Server 2 never came up", isup2);
+ boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
+ boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
+ assertTrue("Server 1 never came up", isup1);
+ assertTrue("Server 2 never came up", isup2);
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ 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));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderWithErrorInStop.stopCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderWithErrorInStop.stopCalled.get());
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*Error while stopping metrics.*");
+ Pattern p = Pattern.compile(".*Error while stopping metrics.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider", found);
+ assertTrue("complains about metrics provider", found);
}
/**
@@ -1569,27 +1489,22 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "metricsProvider.className=BadClass\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "metricsProvider.className=BadClass\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 5000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);
- Assert.assertFalse("Server never came up", isup);
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -1598,15 +1513,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*BadClass.*");
+ Pattern p = Pattern.compile(".*BadClass.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider", found);
+ assertTrue("complains about metrics provider", found);
}
/**
@@ -1625,27 +1539,23 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInStart.class.getName() + "\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInStart.class.getName()
+ + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 5000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);
- Assert.assertFalse("Server never came up", isup);
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -1654,15 +1564,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*MetricsProviderLifeCycleException.*");
+ Pattern p = Pattern.compile(".*MetricsProviderLifeCycleException.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
+ assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}
/**
@@ -1681,27 +1590,23 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInConfigure.class.getName() + "\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInConfigure.class.getName()
+ + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 5000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);
- Assert.assertFalse("Server never came up", isup);
+ 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));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -1710,33 +1615,40 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*MetricsProviderLifeCycleException.*");
+ Pattern p = Pattern.compile(".*MetricsProviderLifeCycleException.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
+ assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}
static class Context {
+
boolean quitFollowing = false;
boolean exitWhenAckNewLeader = false;
NewLeaderAckCallback newLeaderAckCallback = null;
+
}
- static interface NewLeaderAckCallback {
- public void start();
+ interface NewLeaderAckCallback {
+
+ void start();
+
}
- static interface StartForwardingListener {
- public void start();
+ interface StartForwardingListener {
+
+ void start();
+
}
- static interface BeginSnapshotListener {
- public void start();
+ interface BeginSnapshotListener {
+
+ void start();
+
}
static class CustomizedQPMain extends TestQPMain {
@@ -1751,17 +1663,18 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
protected QuorumPeer getQuorumPeer() throws SaslException {
return new CustomQuorumPeer(context);
}
+
}
static class CustomQuorumPeer extends QuorumPeer {
+
private Context context;
private LearnerSyncThrottler throttler = null;
private StartForwardingListener startForwardingListener;
private BeginSnapshotListener beginSnapshotListener;
- public CustomQuorumPeer(Context context)
- throws SaslException {
+ public CustomQuorumPeer(Context context) throws SaslException {
this.context = context;
}
@@ -1776,10 +1689,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(logFactory,
- this, this.getZkDb())) {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
void followLeader() throws InterruptedException {
if (context.quitFollowing) {
@@ -1794,8 +1705,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
void writePacket(QuorumPacket pp, boolean flush) throws IOException {
- if (pp != null && pp.getType() == Leader.ACK
- && context.exitWhenAckNewLeader) {
+ if (pp != null && pp.getType() == Leader.ACK && context.exitWhenAckNewLeader) {
if (context.newLeaderAckCallback != null) {
context.newLeaderAckCallback.start();
}
@@ -1807,11 +1717,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
protected Leader makeLeader(FileTxnSnapLog logFactory) throws IOException, X509Exception {
- return new Leader(this, new LeaderZooKeeperServer(logFactory,
- this, this.getZkDb())) {
+ return new Leader(this, new LeaderZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
- public long startForwarding(LearnerHandler handler,
- long lastSeenZxid) {
+ public long startForwarding(LearnerHandler handler, long lastSeenZxid) {
if (startForwardingListener != null) {
startForwardingListener.start();
}
@@ -1820,12 +1728,10 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
public LearnerSyncThrottler getLearnerSnapSyncThrottler() {
- if (throttler == null){
- throttler = new LearnerSyncThrottler(getMaxConcurrentSnapSyncs(),
- LearnerSyncThrottler.SyncType.SNAP){
+ if (throttler == null) {
+ throttler = new LearnerSyncThrottler(getMaxConcurrentSnapSyncs(), LearnerSyncThrottler.SyncType.SNAP) {
@Override
- public void beginSync(boolean essential)
- throws SyncThrottleException, InterruptedException {
+ public void beginSync(boolean essential) throws SyncThrottleException, InterruptedException {
if (beginSnapshotListener != null) {
beginSnapshotListener.start();
}
@@ -1837,5 +1743,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
};
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
index d6b3774a8..03cb6f06a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,15 +18,15 @@
package org.apache.zookeeper.server.quorum;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
@@ -52,16 +52,12 @@ public class QuorumPeerTest {
Map<Long, QuorumServer> peersView = new HashMap<Long, QuorumServer>();
InetAddress clientIP = InetAddress.getLoopbackAddress();
- peersView.put(Long.valueOf(myId),
- new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
+ peersView.put(Long.valueOf(myId), new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
/**
* QuorumPeer constructor without QuorumVerifier
*/
- QuorumPeer peer1 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime,
- initLimit, syncLimit, connectToLearnerMasterLimit);
+ QuorumPeer peer1 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
String hostString1 = peer1.cnxnFactory.getLocalAddress().getHostString();
assertEquals(clientIP.getHostAddress(), hostString1);
@@ -73,12 +69,8 @@ public class QuorumPeerTest {
*/
peersView.clear();
clientPort = PortAssignment.unique();
- peersView.put(Long.valueOf(myId),
- new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
- QuorumPeer peer2 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime,
- initLimit, syncLimit, connectToLearnerMasterLimit);
+ peersView.put(Long.valueOf(myId), new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
+ QuorumPeer peer2 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
String hostString2 = peer2.cnxnFactory.getLocalAddress().getHostString();
assertEquals(clientIP.getHostAddress(), hostString2);
// cleanup
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java
index 456a3ef9a..fe4d455e1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -17,8 +17,9 @@
*/
/**
- *
+ *
*/
+
package org.apache.zookeeper.server.quorum;
import java.io.File;
@@ -29,30 +30,28 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
import java.util.Properties;
-
+import java.util.Set;
import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZooKeeper;
-import org.junit.After;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.PathUtils;
-import org.apache.zookeeper.server.admin.AdminServer.AdminServerException;
import org.apache.zookeeper.server.admin.JettyAdminServer;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumBase;
+import org.junit.After;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Has some common functionality for tests that work with QuorumPeers. Override
* process(WatchedEvent) to implement the Watcher interface
*/
public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
- protected static final Logger LOG = LoggerFactory
- .getLogger(QuorumPeerTestBase.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(QuorumPeerTestBase.class);
public static final int TIMEOUT = 5000;
@@ -77,15 +76,18 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
public static class TestQPMain extends QuorumPeerMain {
+
public void shutdown() {
// ensure it closes - in particular wait for thread to exit
if (quorumPeer != null) {
QuorumBase.shutdown(quorumPeer);
}
}
+
}
-
+
public static class MainThread implements Runnable {
+
final File confFile;
final File tmpDir;
@@ -111,15 +113,13 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
* @param tickTime initLimit will be 10 and syncLimit will be 5
* @throws IOException
*/
- public MainThread(int myid, int clientPort, String quorumCfgSection,
- Map<String, String> otherConfigs, int tickTime) throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, Map<String, String> otherConfigs, int tickTime) throws IOException {
baseDir = ClientBase.createTmpDir();
this.myid = myid;
this.clientPort = clientPort;
this.quorumCfgSection = quorumCfgSection;
this.otherConfigs = otherConfigs;
- LOG.info("id = " + myid + " tmpDir = " + baseDir + " clientPort = "
- + clientPort);
+ LOG.info("id = " + myid + " tmpDir = " + baseDir + " clientPort = " + clientPort);
confFile = new File(baseDir, "zoo.cfg");
FileWriter fwriter = new FileWriter(confFile);
@@ -164,60 +164,48 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
this(myid, quorumCfgSection, true);
}
- public MainThread(int myid, String quorumCfgSection, Integer secureClientPort, boolean writeDynamicConfigFile)
- throws IOException {
- this(myid, UNSET_STATIC_CLIENTPORT, JettyAdminServer.DEFAULT_PORT, secureClientPort,
- quorumCfgSection, null, null, writeDynamicConfigFile, null);
+ public MainThread(int myid, String quorumCfgSection, Integer secureClientPort, boolean writeDynamicConfigFile) throws IOException {
+ this(myid, UNSET_STATIC_CLIENTPORT, JettyAdminServer.DEFAULT_PORT, secureClientPort, quorumCfgSection, null, null, writeDynamicConfigFile, null);
}
- public MainThread(int myid, String quorumCfgSection, boolean writeDynamicConfigFile)
- throws IOException {
+ public MainThread(int myid, String quorumCfgSection, boolean writeDynamicConfigFile) throws IOException {
this(myid, UNSET_STATIC_CLIENTPORT, quorumCfgSection, writeDynamicConfigFile);
}
- public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile)
- throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile) throws IOException {
this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null, null, writeDynamicConfigFile);
}
-
- public MainThread(int myid, int clientPort, String quorumCfgSection, String peerType, boolean writeDynamicConfigFile)
- throws IOException {
+
+ public MainThread(int myid, int clientPort, String quorumCfgSection, String peerType, boolean writeDynamicConfigFile) throws IOException {
this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null, peerType, writeDynamicConfigFile);
}
- public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile,
- String version) throws IOException {
- this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null,
- null, writeDynamicConfigFile, version);
+ public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile, String version) throws IOException {
+ this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null, null, writeDynamicConfigFile, version);
}
- public MainThread(int myid, int clientPort, String quorumCfgSection, String configs)
- throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, String configs) throws IOException {
this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, configs, null, true);
}
- public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection,
- String configs) throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection, String configs) throws IOException {
this(myid, clientPort, adminServerPort, quorumCfgSection, configs, null, true);
}
- public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection,
- String configs, String peerType, boolean writeDynamicConfigFile)
- throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile) throws IOException {
this(myid, clientPort, adminServerPort, quorumCfgSection, configs, peerType, writeDynamicConfigFile, null);
}
- public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection,
- String configs, String peerType, boolean writeDynamicConfigFile, String version) throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile, String version) throws IOException {
this(myid, clientPort, adminServerPort, null, quorumCfgSection, configs, peerType, writeDynamicConfigFile, version);
}
- public MainThread(int myid, int clientPort, int adminServerPort, Integer secureClientPort,
- String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile, String version)
- throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, Integer secureClientPort, String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile, String version) throws IOException {
tmpDir = ClientBase.createTmpDir();
- LOG.info("id = " + myid + " tmpDir = " + tmpDir + " clientPort = "
- + clientPort + " adminServerPort = " + adminServerPort);
+ LOG.info("id = " + myid
+ + " tmpDir = " + tmpDir
+ + " clientPort = " + clientPort
+ + " adminServerPort = " + adminServerPort);
File dataDir = new File(tmpDir, "data");
if (!dataDir.mkdir()) {
@@ -231,7 +219,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
fwriter.write("initLimit=10\n");
fwriter.write("syncLimit=5\n");
fwriter.write("connectToLearnerMasterLimit=5\n");
- if(configs != null){
+ if (configs != null) {
fwriter.write(configs);
}
@@ -251,7 +239,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
if (secureClientPort != null) {
fwriter.write("secureClientPort=" + secureClientPort + "\n");
}
-
+
if (peerType != null) {
fwriter.write("peerType=" + peerType + "\n");
}
@@ -274,10 +262,9 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
ClientBase.createInitializeFile(dataDir);
}
- private String createDynamicFile(String quorumCfgSection, String version)
- throws IOException {
+ private String createDynamicFile(String quorumCfgSection, String version) throws IOException {
String filename = "zoo.cfg.dynamic";
- if( version != null ){
+ if (version != null) {
filename = filename + "." + version;
}
@@ -297,11 +284,12 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
public File[] getFilesWithPrefix(final String prefix) {
- return tmpDir.listFiles(new FilenameFilter() {
+ return tmpDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(prefix);
- }});
+ }
+ });
}
public File getFileByName(String filename) {
@@ -309,32 +297,25 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
return f.isFile() ? f : null;
}
- public void writeTempDynamicConfigFile(String nextQuorumCfgSection, String version)
- throws IOException {
- File nextDynamicConfigFile = new File(tmpDir,
- "zoo.cfg" + QuorumPeerConfig.nextDynamicConfigFileSuffix);
+ public void writeTempDynamicConfigFile(String nextQuorumCfgSection, String version) throws IOException {
+ File nextDynamicConfigFile = new File(tmpDir, "zoo.cfg" + QuorumPeerConfig.nextDynamicConfigFileSuffix);
FileWriter fwriter = new FileWriter(nextDynamicConfigFile);
- fwriter.write(nextQuorumCfgSection
- + "\n"
- + "version=" + version);
+ fwriter.write(nextQuorumCfgSection + "\n" + "version=" + version);
fwriter.flush();
fwriter.close();
}
- public MainThread(int myid, int clientPort, String quorumCfgSection)
- throws IOException {
- this(myid, clientPort, quorumCfgSection,
- new HashMap<String, String>());
+ public MainThread(int myid, int clientPort, String quorumCfgSection) throws IOException {
+ this(myid, clientPort, quorumCfgSection, new HashMap<String, String>());
}
- public MainThread(int myid, int clientPort, String quorumCfgSection,
- Map<String, String> otherConfigs) throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, Map<String, String> otherConfigs) throws IOException {
this(myid, clientPort, quorumCfgSection, otherConfigs, 4000);
}
Thread currentThread;
- synchronized public void start() {
+ public synchronized void start() {
main = getTestQPMain();
currentThread = new Thread(this);
currentThread.start();
@@ -345,7 +326,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
public void run() {
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
@@ -397,7 +378,6 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
return main.quorumPeer;
}
-
public void deleteBaseDir() {
ClientBase.recursiveDelete(baseDir);
}
@@ -426,12 +406,13 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
// This class holds the servers and clients for those servers
protected static class Servers {
- MainThread mt[];
- ZooKeeper zk[];
+
+ MainThread[] mt;
+ ZooKeeper[] zk;
int[] clientPorts;
public void shutDownAllServers() throws InterruptedException {
- for (MainThread t: mt) {
+ for (MainThread t : mt) {
t.shutdown();
}
}
@@ -451,7 +432,10 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
if (zk[clientIndex] != null) {
zk[clientIndex].close();
}
- zk[clientIndex] = new ZooKeeper("127.0.0.1:" + clientPorts[clientIndex], ClientBase.CONNECTION_TIMEOUT, watcher);
+ zk[clientIndex] = new ZooKeeper(
+ "127.0.0.1:" + clientPorts[clientIndex],
+ ClientBase.CONNECTION_TIMEOUT,
+ watcher);
}
public int findLeader() {
@@ -462,6 +446,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
return -1;
}
+
}
protected Servers LaunchServers(int numServers) throws IOException, InterruptedException {
@@ -481,15 +466,15 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
QuorumPeerMainTest.Servers svrs = new QuorumPeerMainTest.Servers();
svrs.clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
- for(int i = 0; i < SERVER_COUNT; i++) {
+ for (int i = 0; i < SERVER_COUNT; i++) {
svrs.clientPorts[i] = PortAssignment.unique();
- sb.append("server."+i+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+";"+svrs.clientPorts[i]+"\n");
+ sb.append("server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + svrs.clientPorts[i] + "\n");
}
String quorumCfgSection = sb.toString();
svrs.mt = new MainThread[SERVER_COUNT];
svrs.zk = new ZooKeeper[SERVER_COUNT];
- for(int i = 0; i < SERVER_COUNT; i++) {
+ for (int i = 0; i < SERVER_COUNT; i++) {
if (tickTime != null) {
svrs.mt[i] = new MainThread(i, svrs.clientPorts[i], quorumCfgSection, new HashMap<String, String>(), tickTime);
} else {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java
index 5fce0b4ec..3565c562a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,50 +18,48 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.TestableZooKeeper;
+import org.apache.zookeeper.ZKParameterized;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.QuorumBase;
-import org.apache.zookeeper.ZKParameterized;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class QuorumRequestPipelineTest extends QuorumBase {
+
protected ServerState serverState;
protected final CountDownLatch callComplete = new CountDownLatch(1);
protected boolean complete = false;
- protected final static String PARENT_PATH = "/foo";
- protected final static Set<String> CHILDREN = new HashSet<String>(Arrays.asList("1", "2", "3"));
- protected final static String AUTH_PROVIDER = "digest";
- protected final static byte[] AUTH = "hello".getBytes();
- protected final static byte[] DATA = "Hint Water".getBytes();
+ protected static final String PARENT_PATH = "/foo";
+ protected static final Set<String> CHILDREN = new HashSet<String>(Arrays.asList("1", "2", "3"));
+ protected static final String AUTH_PROVIDER = "digest";
+ protected static final byte[] AUTH = "hello".getBytes();
+ protected static final byte[] DATA = "Hint Water".getBytes();
protected TestableZooKeeper zkClient;
@Parameterized.Parameters
public static Collection<Object[]> data() {
- return Arrays.asList(
- new Object[][] {
- {ServerState.LEADING},
- {ServerState.FOLLOWING},
- {ServerState.OBSERVING}});
+ return Arrays.asList(new Object[][]{{ServerState.LEADING}, {ServerState.FOLLOWING}, {ServerState.OBSERVING}});
}
public QuorumRequestPipelineTest(ServerState state) {
@@ -92,61 +90,41 @@ public class QuorumRequestPipelineTest extends QuorumBase {
@Test
public void testCreate() throws Exception {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertArrayEquals(
- String.format("%s Node created (create) with expected value", serverState),
- DATA,
- zkClient.getData(PARENT_PATH, false, null));
+ assertArrayEquals(String.format("%s Node created (create) with expected value", serverState), DATA, zkClient.getData(PARENT_PATH, false, null));
}
@Test
public void testCreate2() throws Exception {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
- Assert.assertArrayEquals(
- String.format("%s Node created (create2) with expected value", serverState),
- DATA,
- zkClient.getData(PARENT_PATH, false, null));
+ assertArrayEquals(String.format("%s Node created (create2) with expected value", serverState), DATA, zkClient.getData(PARENT_PATH, false, null));
}
@Test
public void testDelete() throws Exception {
create2EmptyNode(zkClient, PARENT_PATH);
zkClient.delete(PARENT_PATH, -1);
- Assert.assertNull(
- String.format("%s Node no longer exists", serverState),
- zkClient.exists(PARENT_PATH, false));
+ assertNull(String.format("%s Node no longer exists", serverState), zkClient.exists(PARENT_PATH, false));
}
@Test
public void testExists() throws Exception {
Stat stat = create2EmptyNode(zkClient, PARENT_PATH);
- Assert.assertEquals(
- String.format("%s Exists returns correct node stat", serverState),
- stat,
- zkClient.exists(PARENT_PATH, false));
+ assertEquals(String.format("%s Exists returns correct node stat", serverState), stat, zkClient.exists(PARENT_PATH, false));
}
@Test
public void testSetAndGetData() throws Exception {
create2EmptyNode(zkClient, PARENT_PATH);
zkClient.setData(PARENT_PATH, DATA, -1);
- Assert.assertArrayEquals(
- String.format("%s Node updated with expected value", serverState),
- DATA,
- zkClient.getData(PARENT_PATH, false, null));
+ assertArrayEquals(String.format("%s Node updated with expected value", serverState), DATA, zkClient.getData(PARENT_PATH, false, null));
}
@Test
public void testSetAndGetACL() throws Exception {
create2EmptyNode(zkClient, PARENT_PATH);
- Assert.assertEquals(
- String.format("%s Node has open ACL", serverState),
- Ids.OPEN_ACL_UNSAFE,
- zkClient.getACL(PARENT_PATH, new Stat()));
+ assertEquals(String.format("%s Node has open ACL", serverState), Ids.OPEN_ACL_UNSAFE, zkClient.getACL(PARENT_PATH, new Stat()));
zkClient.setACL(PARENT_PATH, Ids.READ_ACL_UNSAFE, -1);
- Assert.assertEquals(
- String.format("%s Node has world read-only ACL", serverState),
- Ids.READ_ACL_UNSAFE,
- zkClient.getACL(PARENT_PATH, new Stat()));
+ assertEquals(String.format("%s Node has world read-only ACL", serverState), Ids.READ_ACL_UNSAFE, zkClient.getACL(PARENT_PATH, new Stat()));
}
@Test
@@ -155,10 +133,7 @@ public class QuorumRequestPipelineTest extends QuorumBase {
for (String child : CHILDREN) {
create2EmptyNode(zkClient, PARENT_PATH + "/" + child);
}
- Assert.assertEquals(
- String.format("%s Parent has expected children", serverState),
- CHILDREN,
- new HashSet<String>(zkClient.getChildren(PARENT_PATH, false)));
+ assertEquals(String.format("%s Parent has expected children", serverState), CHILDREN, new HashSet<String>(zkClient.getChildren(PARENT_PATH, false)));
}
@Test
@@ -167,10 +142,7 @@ public class QuorumRequestPipelineTest extends QuorumBase {
for (String child : CHILDREN) {
create2EmptyNode(zkClient, PARENT_PATH + "/" + child);
}
- Assert.assertEquals(
- String.format("%s Parent has expected children", serverState),
- CHILDREN,
- new HashSet<String>(zkClient.getChildren(PARENT_PATH, false, null)));
+ assertEquals(String.format("%s Parent has expected children", serverState), CHILDREN, new HashSet<String>(zkClient.getChildren(PARENT_PATH, false, null)));
}
@Test
@@ -186,8 +158,7 @@ public class QuorumRequestPipelineTest extends QuorumBase {
};
zkClient.sync(PARENT_PATH, onSync, null);
callComplete.await(30, TimeUnit.SECONDS);
- Assert.assertTrue(
- String.format("%s Sync completed", serverState),
- complete);
+ assertTrue(String.format("%s Sync completed", serverState), complete);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java
index e47b7ef58..dcd9fcee6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,9 +18,41 @@
package org.apache.zookeeper.server.quorum;
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.apache.zookeeper.test.ClientBase.createTmpDir;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.math.BigInteger;
+import java.net.InetSocketAddress;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLServerSocketFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.common.QuorumX509Util;
@@ -78,43 +110,11 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
-import javax.net.ssl.SSLServerSocketFactory;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivateKey;
-import java.security.Security;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.apache.zookeeper.test.ClientBase.createTmpDir;
-import static org.junit.Assert.fail;
-
public class QuorumSSLTest extends QuorumPeerTestBase {
private static final String SSL_QUORUM_ENABLED = "sslQuorum=true\n";
@@ -151,8 +151,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
private Date certEndTime;
@Rule
- public Timeout timeout = Timeout.builder().withTimeout(5, TimeUnit.MINUTES)
- .withLookingForStuckThread(true).build();
+ public Timeout timeout = Timeout.builder().withTimeout(5, TimeUnit.MINUTES).withLookingForStuckThread(true).build();
@Before
public void setup() throws Exception {
@@ -192,8 +191,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
outputStream.close();
defaultKeyPair = createKeyPair();
- X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, "127.0.0.1", null, null);
+ X509Certificate validCertificate = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ "127.0.0.1",
+ null,
+ null);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
setSSLSystemProperties();
@@ -202,7 +207,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
private void writeKeystore(X509Certificate certificate, KeyPair entityKeyPair, String path) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, PASSWORD);
- keyStore.setKeyEntry("alias", entityKeyPair.getPrivate(), PASSWORD, new Certificate[] { certificate });
+ keyStore.setKeyEntry("alias", entityKeyPair.getPrivate(), PASSWORD, new Certificate[]{certificate});
FileOutputStream outputStream = new FileOutputStream(path);
keyStore.store(outputStream, PASSWORD);
outputStream.flush();
@@ -230,15 +235,12 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
OCSPReq ocspRequest = new OCSPReq(requestBytes);
Req[] requestList = ocspRequest.getRequestList();
- DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build()
- .get(CertificateID.HASH_SHA1);
+ DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
- BasicOCSPRespBuilder responseBuilder =
- new JcaBasicOCSPRespBuilder(rootKeyPair.getPublic(), digestCalculator);
- for ( Req req : requestList ) {
+ BasicOCSPRespBuilder responseBuilder = new JcaBasicOCSPRespBuilder(rootKeyPair.getPublic(), digestCalculator);
+ for (Req req : requestList) {
CertificateID certId = req.getCertID();
- CertificateID revokedCertId =
- new JcaCertificateID(digestCalculator, rootCertificate, revokedCert.getSerialNumber());
+ CertificateID revokedCertId = new JcaCertificateID(digestCalculator, rootCertificate, revokedCert.getSerialNumber());
CertificateStatus certificateStatus;
if (revokedCertId.equals(certId)) {
certificateStatus = new UnknownStatus();
@@ -246,20 +248,16 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
certificateStatus = CertificateStatus.GOOD;
}
- responseBuilder.addResponse(certId, certificateStatus,null);
+ responseBuilder.addResponse(certId, certificateStatus, null);
}
- X509CertificateHolder[] chain = new X509CertificateHolder[] {
- new JcaX509CertificateHolder(rootCertificate)
- };
- ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC")
- .build(rootKeyPair.getPrivate());
- BasicOCSPResp ocspResponse = responseBuilder.build(signer, chain, Calendar.getInstance().getTime() );
+ X509CertificateHolder[] chain = new X509CertificateHolder[]{new JcaX509CertificateHolder(rootCertificate)};
+ ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(rootKeyPair.getPrivate());
+ BasicOCSPResp ocspResponse = responseBuilder.build(signer, chain, Calendar.getInstance().getTime());
responseBytes = new OCSPRespBuilder().build(OCSPRespBuilder.SUCCESSFUL, ocspResponse).getEncoded();
} catch (OperatorException | CertificateEncodingException | OCSPException exception) {
- responseBytes = new OCSPResp(new OCSPResponse(
- new OCSPResponseStatus(OCSPRespBuilder.INTERNAL_ERROR), null)).getEncoded();
+ responseBytes = new OCSPResp(new OCSPResponse(new OCSPResponseStatus(OCSPRespBuilder.INTERNAL_ERROR), null)).getEncoded();
}
Headers rh = httpExchange.getResponseHeaders();
@@ -270,6 +268,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
os.write(responseBytes);
os.close();
}
+
}
private X509Certificate createSelfSignedCertifcate(KeyPair keyPair) throws Exception {
@@ -277,12 +276,16 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
nameBuilder.addRDN(BCStyle.CN, HOSTNAME);
BigInteger serialNumber = new BigInteger(128, new Random());
- X509v3CertificateBuilder certificateBuilder =
- new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, certStartTime, certEndTime,
- nameBuilder.build(), keyPair.getPublic())
- .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
- .addExtension(Extension.keyUsage, true,
- new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
+ JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
+ nameBuilder.build(),
+ serialNumber,
+ certStartTime,
+ certEndTime,
+ nameBuilder.build(),
+ keyPair.getPublic());
+ X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder
+ .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
+ .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
}
@@ -291,8 +294,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
X509v2CRLBuilder builder = new JcaX509v2CRLBuilder(x509Certificate.getIssuerX500Principal(), certStartTime);
builder.addCRLEntry(x509Certificate.getSerialNumber(), certStartTime, CRLReason.cACompromise);
builder.setNextUpdate(certEndTime);
- builder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils()
- .createAuthorityKeyIdentifier(rootCertificate));
+ builder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(rootCertificate));
builder.addExtension(Extension.cRLNumber, false, new CRLNumber(new BigInteger("1000")));
X509CRLHolder cRLHolder = builder.build(contentSigner);
@@ -303,11 +305,16 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
pemWriter.close();
}
- public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey,
- String hostname, String ipAddress, String crlPath, Integer ocspPort)
- throws Exception {
+ public X509Certificate buildEndEntityCert(
+ KeyPair keyPair,
+ X509Certificate caCert,
+ PrivateKey caPrivateKey,
+ String hostname,
+ String ipAddress,
+ String crlPath,
+ Integer ocspPort) throws Exception {
X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
- ContentSigner signer =new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
List<GeneralName> generalNames = new ArrayList<>();
if (hostname != null) {
@@ -318,49 +325,53 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
}
- SubjectPublicKeyInfo entityKeyInfo =
- SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic()
- .getEncoded()));
+ SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(
+ PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
- X509v3CertificateBuilder certificateBuilder =
- new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()),
- certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic())
- .addExtension(Extension.authorityKeyIdentifier, false,
- extensionUtils.createAuthorityKeyIdentifier(holder))
- .addExtension(Extension.subjectKeyIdentifier, false,
- extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
- .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
- .addExtension(Extension.keyUsage, true,
- new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
+ JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
+ holder.getSubject(),
+ new BigInteger(128, new Random()),
+ certStartTime,
+ certEndTime,
+ new X500Name("CN=Test End Entity Certificate"),
+ keyPair.getPublic());
+ X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder
+ .addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder))
+ .addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
+ .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
+ .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
if (!generalNames.isEmpty()) {
- certificateBuilder.addExtension(Extension.subjectAlternativeName, true,
- new GeneralNames(generalNames.toArray(new GeneralName[] {})));
+ certificateBuilder.addExtension(
+ Extension.subjectAlternativeName,
+ true,
+ new GeneralNames(generalNames.toArray(new GeneralName[]{})));
}
if (crlPath != null) {
- DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(
- new GeneralName(GeneralName.uniformResourceIdentifier,"file://" + crlPath)));
+ DistributionPointName distPointOne = new DistributionPointName(
+ new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));
- certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
- new CRLDistPoint(new DistributionPoint[] {
- new DistributionPoint(distPointOne, null, null)
- }));
+ certificateBuilder.addExtension(
+ Extension.cRLDistributionPoints,
+ false,
+ new CRLDistPoint(new DistributionPoint[]{new DistributionPoint(distPointOne, null, null)}));
}
if (ocspPort != null) {
- certificateBuilder.addExtension(Extension.authorityInfoAccess, false,
- new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod,
+ certificateBuilder.addExtension(
+ Extension.authorityInfoAccess,
+ false,
+ new AuthorityInformationAccess(
+ X509ObjectIdentifiers.ocspAccessMethod,
new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
}
return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}
-
private KeyPair createKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
- KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
- BouncyCastleProvider.PROVIDER_NAME);
+ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
keyPairGenerator.initialize(4096);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair;
@@ -375,17 +386,13 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
int portLe2 = PortAssignment.unique();
int portLe3 = PortAssignment.unique();
-
-
- return "server.1=127.0.0.1:" + (portQp1) + ":" + (portLe1) + ";" + clientPortQp1 + "\n" +
- "server.2=127.0.0.1:" + (portQp2) + ":" + (portLe2) + ";" + clientPortQp2 + "\n" +
- "server.3=127.0.0.1:" + (portQp3) + ":" + (portLe3) + ";" + clientPortQp3;
+ return "server.1=127.0.0.1:" + (portQp1) + ":" + (portLe1) + ";" + clientPortQp1
+ + "\n" + "server.2=127.0.0.1:" + (portQp2) + ":" + (portLe2) + ";" + clientPortQp2
+ + "\n" + "server.3=127.0.0.1:" + (portQp3) + ":" + (portLe3) + ";" + clientPortQp3;
}
-
public void setSSLSystemProperties() {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
System.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET, "org.apache.zookeeper.ClientCnxnSocketNetty");
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), validKeystorePath);
System.setProperty(quorumX509Util.getSslKeystorePasswdProperty(), "testpass");
@@ -427,12 +434,11 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1 = new MainThread(1, clientPortQp1, quorumConfiguration, SSL_QUORUM_ENABLED);
q2 = new MainThread(2, clientPortQp2, quorumConfiguration, SSL_QUORUM_ENABLED);
-
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
clearSSLSystemProperties();
@@ -440,7 +446,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
@Test
@@ -450,7 +456,6 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q2 = new MainThread(2, clientPortQp2, quorumConfiguration);
q3 = new MainThread(3, clientPortQp3, quorumConfiguration);
-
Map<Integer, MainThread> members = new HashMap<>();
members.put(clientPortQp1, q1);
members.put(clientPortQp2, q2);
@@ -461,7 +466,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
}
for (int clientPort : members.keySet()) {
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
// Set SSL system properties and port unification, begin restarting servers
@@ -478,7 +483,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
MainThread member = entry.getValue();
member.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
FileWriter fileWriter = new FileWriter(member.getConfFile(), true);
fileWriter.write(config);
@@ -487,15 +492,21 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
member.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
}
@Test
public void testHostnameVerificationWithInvalidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "bleepbloop", null, null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "bleepbloop",
+ null,
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, false);
@@ -504,8 +515,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithInvalidIPAddress() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- null, "140.211.11.105",null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ null,
+ "140.211.11.105",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, false);
@@ -514,8 +531,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithInvalidIpAddressAndInvalidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "bleepbloop", "140.211.11.105", null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "bleepbloop",
+ "140.211.11.105",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, false);
@@ -524,8 +547,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithInvalidIpAddressAndValidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "localhost", "140.211.11.105", null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "localhost",
+ "140.211.11.105",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, true);
@@ -534,8 +563,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithValidIpAddressAndInvalidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "bleepbloop", "127.0.0.1", null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "bleepbloop",
+ "127.0.0.1",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, true);
@@ -555,8 +590,8 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), keystorePath);
@@ -564,15 +599,15 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
setSSLSystemProperties();
System.clearProperty(quorumX509Util.getSslHostnameVerificationEnabledProperty());
@@ -580,17 +615,17 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), keystorePath);
q3.start();
- Assert.assertEquals(expectSuccess, ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3,
- CONNECTION_TIMEOUT));
+ assertEquals(
+ expectSuccess,
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
-
@Test
public void testCertificateRevocationList() throws Exception {
q1 = new MainThread(1, clientPortQp1, quorumConfiguration, SSL_QUORUM_ENABLED);
@@ -599,13 +634,19 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
String revokedInCRLKeystorePath = tmpDir + "/crl_revoked.jks";
String crlPath = tmpDir + "/crl.pem";
- X509Certificate revokedInCRLCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, null, crlPath, null);
+ X509Certificate revokedInCRLCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ crlPath,
+ null);
writeKeystore(revokedInCRLCert, defaultKeyPair, revokedInCRLKeystorePath);
buildCRL(revokedInCRLCert, crlPath);
@@ -615,34 +656,39 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
-
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
setSSLSystemProperties();
System.setProperty(quorumX509Util.getSslCrlEnabledProperty(), "true");
- X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, null, crlPath, null);
+ X509Certificate validCertificate = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ crlPath,
+ null);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), revokedInCRLKeystorePath);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
@Test
@@ -655,12 +701,18 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
String revokedInOCSPKeystorePath = tmpDir + "/ocsp_revoked.jks";
- X509Certificate revokedInOCSPCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, null,null, ocspPort);
+ X509Certificate revokedInOCSPCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ null,
+ ocspPort);
writeKeystore(revokedInOCSPCert, defaultKeyPair, revokedInOCSPKeystorePath);
HttpServer ocspServer = HttpServer.create(new InetSocketAddress(ocspPort), 0);
@@ -674,34 +726,39 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
setSSLSystemProperties();
System.setProperty(quorumX509Util.getSslOcspEnabledProperty(), "true");
- X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate,
- rootKeyPair.getPrivate(),
- HOSTNAME, null,null, ocspPort);
+ X509Certificate validCertificate = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ null,
+ ocspPort);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), revokedInOCSPKeystorePath);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
} finally {
ocspServer.stop(0);
}
@@ -710,7 +767,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testCipherSuites() throws Exception {
// Get default cipher suites from JDK
- SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
+ SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
List<String> defaultCiphers = new ArrayList<String>();
for (String cipher : ssf.getDefaultCipherSuites()) {
if (!cipher.matches(".*EMPTY.*") && cipher.startsWith("TLS") && cipher.contains("RSA")) {
@@ -732,8 +789,8 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
// Use the odd one out for the client
String suiteOfClient = defaultCiphers.get(0);
@@ -744,7 +801,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
@Test
@@ -757,8 +814,8 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslProtocolProperty(), "TLSv1.1");
@@ -766,6 +823,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java
index 62d9a7ba4..c8cbadac5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java
@@ -14,20 +14,19 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.zookeeper.server.quorum;
import static org.junit.Assert.assertEquals;
-
+import java.net.InetSocketAddress;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-import org.junit.Assert;
import org.junit.Test;
-import java.net.InetSocketAddress;
-
public class QuorumServerTest extends ZKTestCase {
+
private String ipv6n1 = "[2500:0:0:0:0:0:1:0]";
private String ipv6n2 = "[2600:0:0:0:0:0:1:0]";
private String ipv4config = "127.0.0.1:1234:1236";
@@ -37,34 +36,32 @@ public class QuorumServerTest extends ZKTestCase {
String provided = ipv4config + ":participant;0.0.0.0:1237";
String expected = ipv4config + ":participant;0.0.0.0:1237";
QuorumServer qs = new QuorumServer(0, provided);
- Assert.assertEquals("Use IP address", expected, qs.toString());
+ assertEquals("Use IP address", expected, qs.toString());
provided = ipv4config + ";0.0.0.0:1237";
expected = ipv4config + ":participant;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Type unspecified", expected, qs.toString());
+ assertEquals("Type unspecified", expected, qs.toString());
provided = ipv4config + ":observer;0.0.0.0:1237";
expected = ipv4config + ":observer;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Observer type", expected, qs.toString());
+ assertEquals("Observer type", expected, qs.toString());
provided = ipv4config + ":participant;1237";
expected = ipv4config + ":participant;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Client address unspecified",
- expected, qs.toString());
+ assertEquals("Client address unspecified", expected, qs.toString());
provided = ipv4config + ":participant;1.2.3.4:1237";
expected = ipv4config + ":participant;1.2.3.4:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Client address specified",
- expected, qs.toString());
+ assertEquals("Client address specified", expected, qs.toString());
provided = "example.com:1234:1236:participant;1237";
expected = "example.com:1234:1236:participant;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Use hostname", expected, qs.toString());
+ assertEquals("Use hostname", expected, qs.toString());
}
@Test
@@ -96,18 +93,14 @@ public class QuorumServerTest extends ZKTestCase {
String[] addrs = new String[]{"127.0.0.1", "[0:0:0:0:0:0:0:1]", "0.0.0.0", "[::]"};
for (int i = 0; i < addrs.length; i++) {
for (int j = i; j < addrs.length; j++) {
- QuorumPeer.QuorumServer server1 =
- new QuorumPeer.QuorumServer(1,
- new InetSocketAddress(ipv6n1, 1234), // peer
- new InetSocketAddress(ipv6n1, 1236), // election
- new InetSocketAddress(addrs[i], 1237) // client
- );
- QuorumPeer.QuorumServer server2 =
- new QuorumPeer.QuorumServer(2,
- new InetSocketAddress(ipv6n2, 1234), // peer
- new InetSocketAddress(ipv6n2, 1236), // election
- new InetSocketAddress(addrs[j], 1237) // client
- );
+ QuorumPeer.QuorumServer server1 = new QuorumPeer.QuorumServer(1, new InetSocketAddress(ipv6n1, 1234), // peer
+ new InetSocketAddress(ipv6n1, 1236), // election
+ new InetSocketAddress(addrs[i], 1237) // client
+ );
+ QuorumPeer.QuorumServer server2 = new QuorumPeer.QuorumServer(2, new InetSocketAddress(ipv6n2, 1234), // peer
+ new InetSocketAddress(ipv6n2, 1236), // election
+ new InetSocketAddress(addrs[j], 1237) // client
+ );
server1.checkAddressDuplicate(server2);
}
}
@@ -115,18 +108,15 @@ public class QuorumServerTest extends ZKTestCase {
@Test(expected = KeeperException.BadArgumentsException.class)
public void testDuplicate() throws KeeperException.BadArgumentsException {
- QuorumPeer.QuorumServer server1 =
- new QuorumPeer.QuorumServer(1,
- new InetSocketAddress(ipv6n1, 1234), // peer
- new InetSocketAddress(ipv6n1, 1236), // election
- new InetSocketAddress(ipv6n1, 1237) // client
- );
- QuorumPeer.QuorumServer server2 =
- new QuorumPeer.QuorumServer(2,
- new InetSocketAddress(ipv6n2, 1234), // peer
- new InetSocketAddress(ipv6n2, 1236), // election
- new InetSocketAddress(ipv6n1, 1237) // client
- );
+ QuorumPeer.QuorumServer server1 = new QuorumPeer.QuorumServer(1, new InetSocketAddress(ipv6n1, 1234), // peer
+ new InetSocketAddress(ipv6n1, 1236), // election
+ new InetSocketAddress(ipv6n1, 1237) // client
+ );
+ QuorumPeer.QuorumServer server2 = new QuorumPeer.QuorumServer(2, new InetSocketAddress(ipv6n2, 1234), // peer
+ new InetSocketAddress(ipv6n2, 1236), // election
+ new InetSocketAddress(ipv6n1, 1237) // client
+ );
server1.checkAddressDuplicate(server2);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java
index ea2a4d385..38739a1f2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,16 +15,16 @@
* 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.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
-
+import javax.security.sasl.SaslException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.common.X509Exception;
@@ -38,18 +38,16 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.security.sasl.SaslException;
-
/**
* This test class contains test cases related to race condition in complete
* ZooKeeper
*/
public class RaceConditionTest extends QuorumPeerTestBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(RaceConditionTest.class);
private static int SERVER_COUNT = 3;
private MainThread[] mt;
@@ -77,15 +75,15 @@ public class RaceConditionTest extends QuorumPeerTestBase {
* after the leader election, not the old LEADING state.
* </pre>
*/
- boolean leaderStateChanged = ClientBase.waitForServerState(leader, 15000,
- QuorumStats.Provider.LOOKING_STATE, QuorumStats.Provider.FOLLOWING_STATE);
+ boolean leaderStateChanged = ClientBase.waitForServerState(leader, 15000, QuorumStats.Provider.LOOKING_STATE, QuorumStats.Provider.FOLLOWING_STATE);
// Wait for the old leader to start completely
- Assert.assertTrue("Failed to bring up the old leader server", ClientBase
- .waitForServerUp("127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
assertTrue(
- "Leader failed to transition to new state. Current state is "
- + leader.getServerState(),
- leaderStateChanged || (leader.getCurrentEpoch() > oldLeaderCurrentEpoch));
+ "Failed to bring up the old leader server",
+ ClientBase.waitForServerUp("127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
+ assertTrue(
+ "Leader failed to transition to new state. Current state is " + leader.getServerState(),
+ leaderStateChanged
+ || (leader.getCurrentEpoch() > oldLeaderCurrentEpoch));
}
@After
@@ -105,18 +103,18 @@ public class RaceConditionTest extends QuorumPeerTestBase {
}
private MainThread[] startQuorum() throws IOException {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
- + ":participant;127.0.0.1:" + clientPorts[i];
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
// start all the servers
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -131,7 +129,8 @@ public class RaceConditionTest extends QuorumPeerTestBase {
// ensure all servers started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
+ assertTrue(
+ "waiting for server " + i + " being up",
ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
return mt;
@@ -157,6 +156,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
}
private static class CustomQuorumPeer extends QuorumPeer {
+
private boolean stopPing;
public CustomQuorumPeer() throws SaslException {
@@ -192,13 +192,10 @@ public class RaceConditionTest extends QuorumPeerTestBase {
* MockSyncRequestProcessor
*/
RequestProcessor finalProcessor = new FinalRequestProcessor(this);
- RequestProcessor toBeAppliedProcessor = new Leader.ToBeAppliedRequestProcessor(finalProcessor,
- getLeader());
- commitProcessor = new CommitProcessor(toBeAppliedProcessor, Long.toString(getServerId()), false,
- getZooKeeperServerListener());
+ RequestProcessor toBeAppliedProcessor = new Leader.ToBeAppliedRequestProcessor(finalProcessor, getLeader());
+ commitProcessor = new CommitProcessor(toBeAppliedProcessor, Long.toString(getServerId()), false, getZooKeeperServerListener());
commitProcessor.start();
- ProposalRequestProcessor proposalProcessor = new MockProposalRequestProcessor(this,
- commitProcessor);
+ ProposalRequestProcessor proposalProcessor = new MockProposalRequestProcessor(this, commitProcessor);
proposalProcessor.initialize();
prepRequestProcessor = new PrepRequestProcessor(this, proposalProcessor);
prepRequestProcessor.start();
@@ -208,6 +205,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
};
return new Leader(this, zk);
}
+
}
private static class MockSyncRequestProcessor extends SyncRequestProcessor {
@@ -222,14 +220,15 @@ public class RaceConditionTest extends QuorumPeerTestBase {
* Add a request so that something is there for SyncRequestProcessor
* to process, while we are in shutdown flow
*/
- Request request = new Request(null, 0, 0, ZooDefs.OpCode.delete,
- ByteBuffer.wrap("/deadLockIssue".getBytes()), null);
+ Request request = new Request(null, 0, 0, ZooDefs.OpCode.delete, ByteBuffer.wrap("/deadLockIssue".getBytes()), null);
processRequest(request);
super.shutdown();
}
+
}
private static class MockProposalRequestProcessor extends ProposalRequestProcessor {
+
public MockProposalRequestProcessor(LeaderZooKeeperServer zks, RequestProcessor nextProcessor) {
super(zks, nextProcessor);
@@ -240,6 +239,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
AckRequestProcessor ackProcessor = new AckRequestProcessor(zks.getLeader());
syncProcessor = new MockSyncRequestProcessor(zks, ackProcessor);
}
+
}
private static class MockTestQPMain extends TestQPMain {
@@ -248,5 +248,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
protected QuorumPeer getQuorumPeer() throws SaslException {
return new CustomQuorumPeer();
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java
index 581cb506b..8efb9d7cc 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,16 +18,11 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.admin.ZooKeeperAdmin;
-import org.apache.zookeeper.common.StringUtils;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -38,8 +33,14 @@ import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.admin.ZooKeeperAdmin;
+import org.apache.zookeeper.common.StringUtils;
+import org.apache.zookeeper.test.ClientBase;
+import org.apache.zookeeper.test.ReconfigTest;
+import org.junit.Before;
+import org.junit.Test;
public class ReconfigBackupTest extends QuorumPeerTestBase {
@@ -62,8 +63,7 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
@Before
public void setup() {
ClientBase.setupTestEnv();
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
/**
@@ -72,41 +72,39 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
@Test
public void testBackupStatic() throws Exception {
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
String[] staticFileContent = new String[SERVER_COUNT];
String[] staticBackupContent = new String[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false);
// check that a dynamic configuration file doesn't exist
- Assert.assertNull("static file backup shouldn't exist before bootup",
- mt[i].getFileByName("zoo.cfg.bak"));
+ assertNull("static file backup shouldn't exist before bootup", mt[i].getFileByName("zoo.cfg.bak"));
staticFileContent[i] = getFileContent(mt[i].confFile);
mt[i].start();
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
File backupFile = mt[i].getFileByName("zoo.cfg.bak");
- Assert.assertNotNull("static file backup should exist", backupFile);
+ assertNotNull("static file backup should exist", backupFile);
staticBackupContent[i] = getFileContent(backupFile);
- Assert.assertEquals(staticFileContent[i], staticBackupContent[i]);
+ assertEquals(staticFileContent[i], staticBackupContent[i]);
}
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -124,10 +122,10 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
final int SERVER_COUNT = 3;
final int NEW_SERVER_COUNT = 5;
- final int clientPorts[] = new int[NEW_SERVER_COUNT];
- final int quorumPorts[] = new int[NEW_SERVER_COUNT];
- final int electionPorts[] = new int[NEW_SERVER_COUNT];
- final String servers[] = new String[NEW_SERVER_COUNT];
+ final int[] clientPorts = new int[NEW_SERVER_COUNT];
+ final int[] quorumPorts = new int[NEW_SERVER_COUNT];
+ final int[] electionPorts = new int[NEW_SERVER_COUNT];
+ final String[] servers = new String[NEW_SERVER_COUNT];
StringBuilder sb = new StringBuilder();
ArrayList<String> oldServers = new ArrayList<String>();
@@ -137,9 +135,7 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
clientPorts[i] = PortAssignment.unique();
quorumPorts[i] = PortAssignment.unique();
electionPorts[i] = PortAssignment.unique();
- servers[i] = "server." + i + "=localhost:" + quorumPorts[i]
- + ":" + electionPorts[i] + ":participant;localhost:"
- + clientPorts[i];
+ servers[i] = "server." + i + "=localhost:" + quorumPorts[i] + ":" + electionPorts[i] + ":participant;localhost:" + clientPorts[i];
newServers.add(servers[i]);
@@ -152,9 +148,9 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String quorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[NEW_SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[NEW_SERVER_COUNT];
- ZooKeeperAdmin zkAdmin[] = new ZooKeeperAdmin[NEW_SERVER_COUNT];
+ MainThread[] mt = new MainThread[NEW_SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[NEW_SERVER_COUNT];
+ ZooKeeperAdmin[] zkAdmin = new ZooKeeperAdmin[NEW_SERVER_COUNT];
// start old cluster
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -166,32 +162,30 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
// test old cluster
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
- zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
zkAdmin[i].addAuthInfo("digest", "super:test".getBytes());
Properties cfg = ReconfigLegacyTest.readPropertiesFromFile(mt[i].confFile);
String filename = cfg.getProperty("dynamicConfigFile", "");
String version = QuorumPeerConfig.getVersionFromFilename(filename);
- Assert.assertNotNull(version);
+ assertNotNull(version);
- String configStr = ReconfigTest.testServerHasConfig(
- zk[i], oldServers, null);
+ String configStr = ReconfigTest.testServerHasConfig(zk[i], oldServers, null);
String configVersion = getVersionFromConfigStr(configStr);
// the version appended to filename should be the same as
// the one of quorum verifier.
- Assert.assertEquals(version, configVersion);
+ assertEquals(version, configVersion);
if (i == 0) {
firstVersion = version;
} else {
- Assert.assertEquals(firstVersion, version);
+ assertEquals(firstVersion, version);
}
}
@@ -205,9 +199,9 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
// wait for new servers to be up running
for (int i = SERVER_COUNT; i < NEW_SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
}
@@ -218,21 +212,18 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String filename = cfg.getProperty("dynamicConfigFile", "");
String version = QuorumPeerConfig.getVersionFromFilename(filename);
- Assert.assertNotNull(version);
+ assertNotNull(version);
- String configStr = ReconfigTest.testServerHasConfig(zk[i],
- newServers, null);
+ String configStr = ReconfigTest.testServerHasConfig(zk[i], newServers, null);
String quorumVersion = getVersionFromConfigStr(configStr);
- Assert.assertEquals(version, quorumVersion);
+ assertEquals(version, quorumVersion);
if (i == 0) {
secondVersion = version;
- Assert.assertTrue(
- Long.parseLong(secondVersion, 16)
- > Long.parseLong(firstVersion, 16));
+ assertTrue(Long.parseLong(secondVersion, 16) > Long.parseLong(firstVersion, 16));
} else {
- Assert.assertEquals(secondVersion, version);
+ assertEquals(secondVersion, version);
}
}
@@ -256,18 +247,16 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
final int SERVER_COUNT = 5;
final int oldServerCount = 3;
final int lagOffServerId = 0;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
StringBuilder oldSb = new StringBuilder();
ArrayList<String> allServers = new ArrayList<String>();
-
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
sb.append(server + "\n");
allServers.add(server);
@@ -281,34 +270,25 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String oldQuorumCfg = oldSb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
-
+ MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
if (i == lagOffServerId) {
mt[i] = new MainThread(i, clientPorts[i], oldQuorumCfg, true, "100000000");
} else {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "200000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "200000000");
}
// before connecting to quorum, servers should have set up dynamic file
// version and pointer. And the lag-off server is using the older
// version dynamic file.
if (i == lagOffServerId) {
- Assert.assertNotNull(
- mt[i].getFileByName("zoo.cfg.dynamic.100000000"));
- Assert.assertNull(
- mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
- Assert.assertTrue(
- mt[i].getPropFromStaticFile("dynamicConfigFile")
- .endsWith(".100000000"));
+ assertNotNull(mt[i].getFileByName("zoo.cfg.dynamic.100000000"));
+ assertNull(mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
+ assertTrue(mt[i].getPropFromStaticFile("dynamicConfigFile").endsWith(".100000000"));
} else {
- Assert.assertNotNull(
- mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
- Assert.assertTrue(
- mt[i].getPropFromStaticFile("dynamicConfigFile")
- .endsWith(".200000000"));
+ assertNotNull(mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
+ assertTrue(mt[i].getPropFromStaticFile("dynamicConfigFile").endsWith(".200000000"));
}
mt[i].start();
@@ -317,32 +297,31 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String dynamicFileContent = null;
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
// we should see that now all servers have the same config of 5 servers
// including the lag-off server.
String configStr = ReconfigTest.testServerHasConfig(zk, allServers, null);
- Assert.assertEquals("200000000", getVersionFromConfigStr(configStr));
-
+ assertEquals("200000000", getVersionFromConfigStr(configStr));
+
List<String> configLines = Arrays.asList(configStr.split("\n"));
Collections.sort(configLines);
String sortedConfigStr = StringUtils.joinStrings(configLines, "\n");
-
- File dynamicConfigFile = mt[i].getFileByName("zoo.cfg.dynamic.200000000");
- Assert.assertNotNull(dynamicConfigFile);
+
+ File dynamicConfigFile = mt[i].getFileByName("zoo.cfg.dynamic.200000000");
+ assertNotNull(dynamicConfigFile);
// All dynamic files created with the same version should have
// same configs, and they should be equal to the config we get from QuorumPeer.
if (i == 0) {
- dynamicFileContent = getFileContent(dynamicConfigFile);
- Assert.assertEquals(sortedConfigStr, dynamicFileContent +
- "version=200000000");
+ dynamicFileContent = getFileContent(dynamicConfigFile);
+ assertEquals(sortedConfigStr, dynamicFileContent + "version=200000000");
} else {
String otherDynamicFileContent = getFileContent(dynamicConfigFile);
- Assert.assertEquals(dynamicFileContent, otherDynamicFileContent);
+ assertEquals(dynamicFileContent, otherDynamicFileContent);
}
zk.close();
@@ -350,12 +329,11 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
// finally, we should also check that the lag-off server has updated
// the dynamic file pointer.
- Assert.assertTrue(
- mt[lagOffServerId].getPropFromStaticFile("dynamicConfigFile")
- .endsWith(".200000000"));
+ assertTrue(mt[lagOffServerId].getPropFromStaticFile("dynamicConfigFile").endsWith(".200000000"));
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].shutdown();
}
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java
index 4d07ffa71..bff6cbf0e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,17 +15,17 @@
* 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.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
-
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
@@ -38,21 +38,20 @@ import org.apache.zookeeper.server.quorum.flexible.QuorumMaj;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ReconfigDuringLeaderSyncTest.class);
private static int SERVER_COUNT = 3;
private MainThread[] mt;
@Before
public void setup() {
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
QuorumPeerConfig.setReconfigEnabled(true);
}
@@ -70,14 +69,14 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
@Test
public void testDuringLeaderSync() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT + 1];
+ final int[] clientPorts = new int[SERVER_COUNT + 1];
StringBuilder sb = new StringBuilder();
String[] serverConfig = new String[SERVER_COUNT + 1];
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
serverConfig[i] = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
- + ":participant;127.0.0.1:" + clientPorts[i];
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(serverConfig[i] + "\n");
}
String currentQuorumCfgSection = sb.toString();
@@ -91,20 +90,23 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
// ensure all servers started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
CountdownWatcher watch = new CountdownWatcher();
- ZooKeeperAdmin preReconfigClient = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[0],
- ClientBase.CONNECTION_TIMEOUT, watch);
+ ZooKeeperAdmin preReconfigClient = new ZooKeeperAdmin(
+ "127.0.0.1:" + clientPorts[0],
+ ClientBase.CONNECTION_TIMEOUT,
+ watch);
preReconfigClient.addAuthInfo("digest", "super:test".getBytes());
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
// new server joining
int joinerId = SERVER_COUNT;
clientPorts[joinerId] = PortAssignment.unique();
- serverConfig[joinerId] = "server." + joinerId + "=127.0.0.1:" + PortAssignment.unique() + ":"
- + PortAssignment.unique() + ":participant;127.0.0.1:" + clientPorts[joinerId];
+ serverConfig[joinerId] = "server." + joinerId + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[joinerId];
// Find leader id.
int leaderId = -1;
@@ -157,8 +159,10 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
}
}
watch = new CountdownWatcher();
- ZooKeeper postReconfigClient = new ZooKeeper("127.0.0.1:" + clientPorts[joinerId],
- ClientBase.CONNECTION_TIMEOUT, watch);
+ ZooKeeper postReconfigClient = new ZooKeeper(
+ "127.0.0.1:" + clientPorts[joinerId],
+ ClientBase.CONNECTION_TIMEOUT,
+ watch);
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
// do one successful operation on the newly added node
postReconfigClient.create("/reconfigIssue", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -166,8 +170,9 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
// verify that joiner has up-to-date config, including all four servers.
for (long j = 0; j <= SERVER_COUNT; j++) {
- assertNotNull("server " + j + " is not present in the new quorum",
- qp.getQuorumVerifier().getVotingMembers().get(j));
+ assertNotNull(
+ "server " + j + " is not present in the new quorum",
+ qp.getQuorumVerifier().getVotingMembers().get(j));
}
// close clients
@@ -205,13 +210,11 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
}
private static class CustomQuorumPeer extends QuorumPeer {
+
private boolean newLeaderMessage = false;
- public CustomQuorumPeer(Map<Long, QuorumServer> quorumPeers, File snapDir, File logDir, int clientPort,
- int electionAlg, long myid, int tickTime, int initLimit, int syncLimit, int connectToLearnerMasterLimit)
- throws IOException {
- super(quorumPeers, snapDir, logDir, electionAlg, myid, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, false,
- ServerCnxnFactory.createFactory(new InetSocketAddress(clientPort), -1), new QuorumMaj(quorumPeers));
+ public CustomQuorumPeer(Map<Long, QuorumServer> quorumPeers, File snapDir, File logDir, int clientPort, int electionAlg, long myid, int tickTime, int initLimit, int syncLimit, int connectToLearnerMasterLimit) throws IOException {
+ super(quorumPeers, snapDir, logDir, electionAlg, myid, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, false, ServerCnxnFactory.createFactory(new InetSocketAddress(clientPort), -1), new QuorumMaj(quorumPeers));
}
/**
@@ -248,16 +251,14 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
}
};
}
+
}
private static class MockTestQPMain extends TestQPMain {
+
@Override
- public void runFromConfig(QuorumPeerConfig config)
- throws IOException, AdminServerException {
- quorumPeer = new CustomQuorumPeer(config.getQuorumVerifier().getAllMembers(), config.getDataDir(),
- config.getDataLogDir(), config.getClientPortAddress().getPort(), config.getElectionAlg(),
- config.getServerId(), config.getTickTime(), config.getInitLimit(), config.getSyncLimit(),
- config.getConnectToLearnerMasterLimit());
+ public void runFromConfig(QuorumPeerConfig config) throws IOException, AdminServerException {
+ quorumPeer = new CustomQuorumPeer(config.getQuorumVerifier().getAllMembers(), config.getDataDir(), config.getDataLogDir(), config.getClientPortAddress().getPort(), config.getElectionAlg(), config.getServerId(), config.getTickTime(), config.getInitLimit(), config.getSyncLimit(), config.getConnectToLearnerMasterLimit());
quorumPeer.setConfigFileName(config.getConfigFilename());
quorumPeer.start();
try {
@@ -266,5 +267,7 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
LOG.warn("Quorum Peer interrupted", e);
}
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java
index bd9e5881c..f28979bf7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,13 +19,13 @@
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NewConfigNoQuorum;
import org.apache.zookeeper.ZooKeeper;
@@ -35,7 +35,6 @@ import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
import org.apache.zookeeper.test.ReconfigTest;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,8 +45,7 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
@Before
public void setup() {
QuorumPeerConfig.setReconfigEnabled(true);
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
@After
@@ -79,9 +77,10 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
for (int i = 1; i <= 5; i++) {
members.add("server." + i + "=127.0.0.1:"
- + qu.getPeer(i).peer.getQuorumAddress().getPort() + ":"
- + qu.getPeer(i).peer.getElectionAddress().getPort() + ";"
- + "127.0.0.1:" + qu.getPeer(i).peer.getClientPort());
+ + qu.getPeer(i).peer.getQuorumAddress().getPort()
+ + ":" + qu.getPeer(i).peer.getElectionAddress().getPort()
+ + ";" + "127.0.0.1:"
+ + qu.getPeer(i).peer.getClientPort());
}
// Change the quorum system from majority to hierarchical.
@@ -92,12 +91,12 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
List<String> leavingServers = new ArrayList<String>();
leavingServers.add("3");
try {
- zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
- Assert.fail("Reconfig should have failed since the current config isn't Majority QS");
+ zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
+ fail("Reconfig should have failed since the current config isn't Majority QS");
} catch (KeeperException.BadArgumentsException e) {
// We expect this to happen.
} catch (Exception e) {
- Assert.fail("Should have been BadArgumentsException!");
+ fail("Should have been BadArgumentsException!");
}
ReconfigTest.closeAllHandles(zkArr, zkAdminArr);
@@ -122,12 +121,12 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
leavingServers.add("2");
leavingServers.add("3");
try {
- zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
- Assert.fail("Reconfig should have failed since the current config version is not 8");
+ zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
+ fail("Reconfig should have failed since the current config version is not 8");
} catch (KeeperException.BadArgumentsException e) {
// We expect this to happen.
} catch (Exception e) {
- Assert.fail("Should have been BadArgumentsException!");
+ fail("Should have been BadArgumentsException!");
}
ReconfigTest.closeAllHandles(zkArr, zkAdminArr);
@@ -148,12 +147,12 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
List<String> leavingServers = new ArrayList<String>();
leavingServers.add("3");
try {
- zkAdminArr[1].reconfigure(null, leavingServers, null, 8, null);
- Assert.fail("Reconfig should have failed since the current config version is not 8");
+ zkAdminArr[1].reconfigure(null, leavingServers, null, 8, null);
+ fail("Reconfig should have failed since the current config version is not 8");
} catch (KeeperException.BadVersionException e) {
// We expect this to happen.
} catch (Exception e) {
- Assert.fail("Should have been BadVersionException!");
+ fail("Should have been BadVersionException!");
}
ReconfigTest.closeAllHandles(zkArr, zkAdminArr);
@@ -190,36 +189,33 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
String currentQuorumCfgSection = sb.toString();
String nextQuorumCfgSection = currentQuorumCfgSection.replace("observer", "participant");
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
- ZooKeeperAdmin zkAdmin[] = new ZooKeeperAdmin[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
+ ZooKeeperAdmin[] zkAdmin = new ZooKeeperAdmin[SERVER_COUNT];
// Server 0 stays down
for (int i = 1; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, ports[i][2], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, ports[i][2], currentQuorumCfgSection, true, "100000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
- zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
+ zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
zkAdmin[i].addAuthInfo("digest", "super:test".getBytes());
}
for (int i = 1; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 2));
}
try {
zkAdmin[1].reconfigure("", "", nextQuorumCfgSection, -1, new Stat());
- Assert.fail("Reconfig should have failed with NewConfigNoQuorum");
+ fail("Reconfig should have failed with NewConfigNoQuorum");
} catch (NewConfigNoQuorum e) {
// This is expected case since server 0 is down and 3 can't vote
// (observer in current role) and we need 3 votes from 0, 1, 2, 3,
} catch (Exception e) {
- Assert.fail("Reconfig should have failed with NewConfigNoQuorum");
+ fail("Reconfig should have failed with NewConfigNoQuorum");
}
// In this scenario to change 3's role to participant we need to remove it first
ArrayList<String> leavingServers = new ArrayList<String>();
@@ -241,4 +237,5 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
mt[i].shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java
index db399b71b..d6eba89a3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -20,13 +20,13 @@ package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertEquals;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
@@ -34,7 +34,6 @@ import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,8 +45,7 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
public void setup() {
ClientBase.setupTestEnv();
QuorumPeerConfig.setReconfigEnabled(true);
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
/**
@@ -58,62 +56,60 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
*/
@Test
public void testConfigFileBackwardCompatibility() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
ArrayList<String> allServers = new ArrayList<String>();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
allServers.add(server);
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// Start the servers with a static config file, without a dynamic
// config file.
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, "participant", false);
// check that a dynamic configuration file doesn't exist
- Assert.assertEquals( mt[i].getDynamicFiles().length, 0 );
+ assertEquals(mt[i].getDynamicFiles().length, 0);
mt[i].start();
}
// Check that the servers are up, have the right config and can process operations.
// Check that the static config was split into static and dynamic files correctly.
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
File[] dynamicFiles = mt[i].getDynamicFiles();
- Assert.assertTrue( dynamicFiles.length== 1 );
+ assertTrue(dynamicFiles.length == 1);
ReconfigTest.testServerHasConfig(zk[i], allServers, null);
// check that static config file doesn't include membership info
// and has a pointer to the dynamic configuration file
// check that static config file doesn't include peerType info
Properties cfg = readPropertiesFromFile(mt[i].confFile);
for (int j = 0; j < SERVER_COUNT; j++) {
- Assert.assertFalse(cfg.containsKey("server." + j));
+ assertFalse(cfg.containsKey("server." + j));
}
- Assert.assertFalse(cfg.containsKey("peerType"));
- Assert.assertTrue(cfg.containsKey("dynamicConfigFile"));
- Assert.assertFalse(cfg.containsKey("clientPort"));
+ assertFalse(cfg.containsKey("peerType"));
+ assertTrue(cfg.containsKey("dynamicConfigFile"));
+ assertFalse(cfg.containsKey("clientPort"));
// check that the dynamic configuration file contains the membership info
cfg = readPropertiesFromFile(dynamicFiles[0]);
for (int j = 0; j < SERVER_COUNT; j++) {
String serverLine = cfg.getProperty("server." + j, "");
- Assert.assertEquals(allServers.get(j), "server." + j + "="
- + serverLine);
+ assertEquals(allServers.get(j), "server." + j + "=" + serverLine);
}
- Assert.assertFalse(cfg.containsKey("dynamicConfigFile"));
+ assertFalse(cfg.containsKey("dynamicConfigFile"));
}
ReconfigTest.testNormalOperation(zk[0], zk[1]);
@@ -126,9 +122,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
mt[i].start();
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
ReconfigTest.testServerHasConfig(zk[i], allServers, null);
}
@@ -149,9 +145,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
*/
@Test
public void testReconfigRemoveClientFromStatic() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
- final int quorumPorts[] = new int[SERVER_COUNT];
- final int electionPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
+ final int[] quorumPorts = new int[SERVER_COUNT];
+ final int[] electionPorts = new int[SERVER_COUNT];
final int changedServerId = 0;
final int newClientPort = PortAssignment.unique();
@@ -165,12 +161,11 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
quorumPorts[i] = PortAssignment.unique();
electionPorts[i] = PortAssignment.unique();
- String server = "server." + i + "=localhost:" + quorumPorts[i]
- +":" + electionPorts[i] + ":participant";
+ String server = "server." + i + "=localhost:" + quorumPorts[i] + ":" + electionPorts[i] + ":participant";
allServers.add(server);
sb.append(server + "\n");
- if(i == changedServerId) {
+ if (i == changedServerId) {
newServers.add(server + ";0.0.0.0:" + newClientPort);
} else {
newServers.add(server);
@@ -178,9 +173,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
}
String quorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
- ZooKeeperAdmin zkAdmin[] = new ZooKeeperAdmin[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
+ ZooKeeperAdmin[] zkAdmin = new ZooKeeperAdmin[SERVER_COUNT];
// Start the servers with a static config file, without a dynamic config file.
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -191,19 +186,18 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
// Check that when a server starts from old style config, it should keep the client
// port in static config file.
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
- zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
zkAdmin[i].addAuthInfo("digest", "super:test".getBytes());
ReconfigTest.testServerHasConfig(zk[i], allServers, null);
Properties cfg = readPropertiesFromFile(mt[i].confFile);
- Assert.assertTrue(cfg.containsKey("dynamicConfigFile"));
- Assert.assertTrue(cfg.containsKey("clientPort"));
+ assertTrue(cfg.containsKey("dynamicConfigFile"));
+ assertTrue(cfg.containsKey("clientPort"));
}
ReconfigTest.testNormalOperation(zk[0], zk[1]);
@@ -221,9 +215,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
ReconfigTest.testServerHasConfig(zk[i], newServers, null);
Properties staticCfg = readPropertiesFromFile(mt[i].confFile);
if (i == changedServerId) {
- Assert.assertFalse(staticCfg.containsKey("clientPort"));
+ assertFalse(staticCfg.containsKey("clientPort"));
} else {
- Assert.assertTrue(staticCfg.containsKey("clientPort"));
+ assertTrue(staticCfg.containsKey("clientPort"));
}
}
@@ -252,39 +246,36 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
*/
@Test(timeout = 120000)
public void testRestartZooKeeperServer() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false);
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false);
mt[i].start();
}
// ensure server started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + clientPorts[0]);
- String zNodePath="/serverRestartTest";
+ String zNodePath = "/serverRestartTest";
String data = "originalData";
- zk.create(zNodePath, data.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(zNodePath, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
/**
@@ -296,9 +287,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
mt[1].start();
// ensure server started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
zk = ClientBase.createZKClient("127.0.0.1:" + clientPorts[0]);
@@ -310,4 +301,5 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
mt[i].shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java
index 261ff6c82..ee0fb4a03 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,20 +19,21 @@
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ReconfigRecoveryTest extends QuorumPeerTestBase {
+
@Before
public void setup() {
QuorumPeerConfig.setReconfigEnabled(true);
@@ -48,7 +49,7 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 3 in next config
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
ArrayList<String> allServers = new ArrayList<String>();
@@ -57,40 +58,37 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
allServers.add(server);
sb.append(server + "\n");
- if (i == 1)
+ if (i == 1) {
currentQuorumCfgSection = sb.toString();
+ }
}
nextQuorumCfgSection = sb.toString();
// Both servers 0 and 1 will have the .next config file, which means
// for them that a reconfiguration was in progress when they failed
// and the leader will complete it
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT - 1; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "100000000");
// note that we should run the server, shut it down and only then
// simulate a reconfig in progress by writing the temp file, but here no
// other server is competing with them in FLE, so we can skip this step
// (server 2 is booted after FLE ends)
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
- Assert.assertTrue("waiting for server 0 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + clientPorts[0],
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 1 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + clientPorts[1],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 0 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[0], CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[1], CONNECTION_TIMEOUT));
int leader = mt[0].main.quorumPeer.leader == null ? 1 : 0;
@@ -103,12 +101,11 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
String newServerInitialConfig = sb.toString();
mt[2] = new MainThread(2, clientPorts[2], newServerInitialConfig);
mt[2].start();
- zk[2] = new ZooKeeper("127.0.0.1:" + clientPorts[2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[2] = new ZooKeeper("127.0.0.1:" + clientPorts[2], ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("waiting for server 2 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + clientPorts[2],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[2], CONNECTION_TIMEOUT));
ReconfigTest.testServerHasConfig(zk[0], allServers, null);
ReconfigTest.testServerHasConfig(zk[1], allServers, null);
@@ -134,8 +131,8 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 5 in next config
final int SERVER_COUNT = 5;
- final int clientPorts[] = new int[SERVER_COUNT];
- final int oldClientPorts[] = new int[2];
+ final int[] clientPorts = new int[SERVER_COUNT];
+ final int[] oldClientPorts = new int[2];
StringBuilder sb = new StringBuilder();
String server;
@@ -145,9 +142,8 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i < 2; i++) {
oldClientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + oldClientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + oldClientPorts[i];
sb.append(server + "\n");
}
@@ -162,31 +158,28 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
} else {
role = "participant";
}
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":" + role
- + ";localhost:" + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":"
+ + role + ";localhost:" + clientPorts[i];
allServersNext.add(server);
sb.append(server + "\n");
}
nextQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// run servers 0 and 1 normally
for (int i = 0; i < 2; i++) {
- mt[i] = new MainThread(i, oldClientPorts[i], currentQuorumCfg,
- true, "100000000");
+ mt[i] = new MainThread(i, oldClientPorts[i], currentQuorumCfg, true, "100000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + oldClientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + oldClientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
for (int i = 0; i < 2; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp(
- "127.0.0.1:" + oldClientPorts[i],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + oldClientPorts[i], CONNECTION_TIMEOUT
+ * 2));
}
ReconfigTest.testNormalOperation(zk[0], zk[1]);
@@ -198,32 +191,29 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
}
for (int i = 0; i < 2; i++) {
- Assert.assertTrue(
- "waiting for server " + i + " being up",
- ClientBase.waitForServerDown("127.0.0.1:"
- + oldClientPorts[i], CONNECTION_TIMEOUT * 2));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerDown(
+ "127.0.0.1:"
+ + oldClientPorts[i], CONNECTION_TIMEOUT
+ * 2));
}
for (int i = 0; i < 2; i++) {
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
// new members are initialized with current config + the new server
for (int i = 2; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfg
- + allServersNext.get(i));
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfg + allServersNext.get(i));
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT * 2));
ReconfigTest.testServerHasConfig(zk[i], allServersNext, null);
}
@@ -248,7 +238,7 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 5 in next config
final int SERVER_COUNT = 5;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
@@ -256,30 +246,28 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
sb.append(server + "\n");
- if (i == 1)
+ if (i == 1) {
currentQuorumCfgSection = sb.toString();
+ }
}
nextQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// Both servers 0 and 1 will have the .next config file, which means
// for them that a reconfiguration was in progress when they failed
for (int i = 0; i < 2; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "100000000");
// note that we should run the server, shut it down and only then
// simulate a reconfig in progress by writing the temp file, but here no
// other server is competing with them in FLE, so we can skip this step
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
Thread.sleep(CONNECTION_TIMEOUT * 2);
@@ -287,9 +275,9 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// make sure servers 0, 1 don't come online - this should be the case
// since they can't complete the reconfig
for (int i = 0; i < 2; i++) {
- Assert.assertFalse("server " + i + " is up but shouldn't be",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT / 10));
+ assertFalse(
+ "server " + i + " is up but shouldn't be",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT / 10));
}
for (int i = 0; i < 2; i++) {
@@ -308,7 +296,7 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 5 in next config
final int SERVER_COUNT = 5;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
@@ -317,29 +305,28 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
ArrayList<String> allServers = new ArrayList<String>();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
allServers.add(server);
sb.append(server + "\n");
- if (i == 1) currentQuorumCfgSection = sb.toString();
+ if (i == 1) {
+ currentQuorumCfgSection = sb.toString();
+ }
}
nextQuorumCfgSection = sb.toString();
// lets start servers 2, 3, 4 with the new config
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 2; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], nextQuorumCfgSection,
- true, "200000000");
+ mt[i] = new MainThread(i, clientPorts[i], nextQuorumCfgSection, true, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
for (int i = 2; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
ReconfigTest.testNormalOperation(zk[2], zk[3]);
@@ -350,26 +337,24 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// for them that a reconfiguration was in progress when they failed
// and the leader will complete it.
for (int i = 0; i < 2; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "100000000");
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
// servers 0 and 1 should connect to all servers, including the one in
// their .next file during startup, and will find the next config and join it
for (int i = 0; i < 2; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT * 2));
}
// make sure they joined the new config without any change to it
- Assert.assertEquals(epoch, mt[0].main.quorumPeer.getAcceptedEpoch());
- Assert.assertEquals(epoch, mt[1].main.quorumPeer.getAcceptedEpoch());
- Assert.assertEquals(epoch, mt[2].main.quorumPeer.getAcceptedEpoch());
+ assertEquals(epoch, mt[0].main.quorumPeer.getAcceptedEpoch());
+ assertEquals(epoch, mt[1].main.quorumPeer.getAcceptedEpoch());
+ assertEquals(epoch, mt[2].main.quorumPeer.getAcceptedEpoch());
ReconfigTest.testServerHasConfig(zk[0], allServers, null);
ReconfigTest.testServerHasConfig(zk[1], allServers, null);
@@ -409,41 +394,39 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
ArrayList<String> allServersNext = new ArrayList<String>();
sb = new StringBuilder();
for (int i = 2; i < SERVER_COUNT; i++) {
- String server = "server." + i + "=localhost:" + ports[i][0] + ":"
- + ports[i][1] + ":participant;localhost:" + ports[i][2];
+ String server = "server." + i + "=localhost:" + ports[i][0] + ":" + ports[i][1]
+ + ":participant;localhost:" + ports[i][2];
allServersNext.add(server);
sb.append(server + "\n");
}
nextQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// start server 2 with old config, where it is an observer
- mt[2] = new MainThread(2, ports[2][2], currentQuorumCfgSection,
- true, "100000000");
+ mt[2] = new MainThread(2, ports[2][2], currentQuorumCfgSection, true, "100000000");
mt[2].start();
- zk[2] = new ZooKeeper("127.0.0.1:" + ports[2][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[2] = new ZooKeeper("127.0.0.1:" + ports[2][2], ClientBase.CONNECTION_TIMEOUT, this);
// start server 3 with new config
- mt[3] = new MainThread(3, ports[3][2], nextQuorumCfgSection,
- true, "200000000");
+ mt[3] = new MainThread(3, ports[3][2], nextQuorumCfgSection, true, "200000000");
mt[3].start();
- zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2], ClientBase.CONNECTION_TIMEOUT, this);
for (int i = 2; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 2));
ReconfigTest.testServerHasConfig(zk[i], allServersNext, null);
}
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[2], null, null));
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[3], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[2], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[3], null, null));
ReconfigTest.testNormalOperation(zk[2], zk[2]);
ReconfigTest.testNormalOperation(zk[3], zk[2]);
@@ -481,22 +464,20 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
currentQuorumCfg = sb.toString();
// Run servers 0..2 for a while
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 0; i <= 2; i++) {
- mt[i] = new MainThread(i, ports[i][2], currentQuorumCfg
- , true, "100000000");
+ mt[i] = new MainThread(i, ports[i][2], currentQuorumCfg, true, "100000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
}
ReconfigTest.testNormalOperation(zk[0], zk[2]);
for (int i = 0; i <= 2; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 2));
}
// shut servers 0..2 down
@@ -509,8 +490,8 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
ArrayList<String> allServersNext = new ArrayList<String>();
sb = new StringBuilder();
for (int i = 2; i < SERVER_COUNT; i++) {
- String server = "server." + i + "=localhost:" + ports[i][0] + ":"
- + ports[i][1] + ":participant;localhost:" + ports[i][2];
+ String server = "server." + i + "=localhost:" + ports[i][0] + ":" + ports[i][1]
+ + ":participant;localhost:" + ports[i][2];
allServersNext.add(server);
sb.append(server + "\n");
}
@@ -521,30 +502,29 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i <= 2; i++) {
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
}
// new server 3 has still its invalid joiner config - everyone in old
// config + itself
- mt[3] = new MainThread(3, ports[3][2], currentQuorumCfg
- + allServersNext.get(1));
+ mt[3] = new MainThread(3, ports[3][2], currentQuorumCfg + allServersNext.get(1));
mt[3].start();
- zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2], ClientBase.CONNECTION_TIMEOUT, this);
for (int i = 2; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 3));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 3));
ReconfigTest.testServerHasConfig(zk[i], allServersNext, null);
}
ReconfigTest.testNormalOperation(zk[0], zk[2]);
ReconfigTest.testNormalOperation(zk[3], zk[1]);
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[2], null, null));
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[3], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[2], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[3], null, null));
for (int i = 0; i < SERVER_COUNT; i++) {
zk[i].close();
@@ -570,16 +550,15 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
* Creates a configuration string for servers 0..numServers-1 Ids in
* observerIds correspond to observers, other ids are for participants.
*/
- public static StringBuilder generateConfig(int numServers, int[][] ports,
- Set<Integer> observerIds) {
+ public static StringBuilder generateConfig(int numServers, int[][] ports, Set<Integer> observerIds) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numServers; i++) {
- String server = "server." + i + "=localhost:" + ports[i][0] + ":"
- + ports[i][1] + ":"
- + (observerIds.contains(i) ? "observer" : "participant")
- + ";localhost:" + ports[i][2];
+ String server = "server." + i + "=localhost:" + ports[i][0] + ":" + ports[i][1] + ":"
+ + (observerIds.contains(i) ? "observer" : "participant")
+ + ";localhost:" + ports[i][2];
sb.append(server + "\n");
}
return sb;
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java
index 65ec469ee..c4d2bd7ea 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,26 +18,26 @@
package org.apache.zookeeper.server.quorum;
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Map;
-import java.util.Set;
-import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.ArrayList;
-
-import org.apache.zookeeper.ZooKeeper;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Test;
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
/**
* ReconfigRollingRestartCompatibilityTest - we want to make sure that users
* can continue using the rolling restart approach when reconfig feature is disabled.
@@ -49,6 +49,7 @@ import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
* See ZOOKEEPER-2819 for more details.
*/
public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase {
+
private static final String ZOO_CFG_BAK_FILE = "zoo.cfg.bak";
Map<Integer, Integer> clientPorts = new HashMap<>(5);
@@ -59,9 +60,8 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
String server;
for (int i = 0; i < serverCount; i++) {
clientPorts.put(i, PortAssignment.unique());
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts.get(i);
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts.get(i);
serverAddress.put(i, server);
sb.append(server + "\n");
}
@@ -72,9 +72,8 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
StringBuilder sb = new StringBuilder();
for (Integer sid : sidsToAdd) {
clientPorts.put(sid, PortAssignment.unique());
- serverAddress.put(sid, "server." + sid + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts.get(sid));
+ serverAddress.put(sid, "server." + sid + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts.get(sid));
}
for (Integer sid : sidsToRemove) {
@@ -92,30 +91,23 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
@Test(timeout = 60000)
// Verify no zoo.cfg.dynamic and zoo.cfg.bak files existing locally
// when reconfig feature flag is off by default.
- public void testNoLocalDynamicConfigAndBackupFiles()
- throws InterruptedException, IOException {
+ public void testNoLocalDynamicConfigAndBackupFiles() throws InterruptedException, IOException {
int serverCount = 3;
String config = generateNewQuorumConfig(serverCount);
- QuorumPeerTestBase.MainThread mt[] = new QuorumPeerTestBase.MainThread[serverCount];
+ QuorumPeerTestBase.MainThread[] mt = new QuorumPeerTestBase.MainThread[serverCount];
String[] staticFileContent = new String[serverCount];
for (int i = 0; i < serverCount; i++) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
}
for (int i = 0; i < serverCount; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
- Assert.assertNull("static file backup (zoo.cfg.bak) shouldn't exist!",
- mt[i].getFileByName(ZOO_CFG_BAK_FILE));
- Assert.assertNull("dynamic configuration file (zoo.cfg.dynamic.*) shouldn't exist!",
- mt[i].getFileByName(mt[i].getQuorumPeer().getNextDynamicConfigFilename()));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
+ assertNull("static file backup (zoo.cfg.bak) shouldn't exist!", mt[i].getFileByName(ZOO_CFG_BAK_FILE));
+ assertNull("dynamic configuration file (zoo.cfg.dynamic.*) shouldn't exist!", mt[i].getFileByName(mt[i].getQuorumPeer().getNextDynamicConfigFilename()));
staticFileContent[i] = Files.readAllLines(mt[i].confFile.toPath(), StandardCharsets.UTF_8).toString();
- Assert.assertTrue("static config file should contain server entry " + serverAddress.get(i),
- staticFileContent[i].contains(serverAddress.get(i)));
+ assertTrue("static config file should contain server entry " + serverAddress.get(i), staticFileContent[i].contains(serverAddress.get(i)));
}
for (int i = 0; i < serverCount; i++) {
@@ -132,18 +124,15 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
int serverCount = 3;
String config = generateNewQuorumConfig(serverCount);
List<String> joiningServers = new ArrayList<>();
- QuorumPeerTestBase.MainThread mt[] = new QuorumPeerTestBase.MainThread[serverCount];
+ QuorumPeerTestBase.MainThread[] mt = new QuorumPeerTestBase.MainThread[serverCount];
for (int i = 0; i < serverCount; ++i) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
joiningServers.add(serverAddress.get(i));
}
for (int i = 0; i < serverCount; ++i) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
}
for (int i = 0; i < serverCount; ++i) {
@@ -166,19 +155,16 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
public void testRollingRestartWithMembershipChange() throws Exception {
int serverCount = 3;
String config = generateNewQuorumConfig(serverCount);
- QuorumPeerTestBase.MainThread mt[] = new QuorumPeerTestBase.MainThread[serverCount];
+ QuorumPeerTestBase.MainThread[] mt = new QuorumPeerTestBase.MainThread[serverCount];
List<String> joiningServers = new ArrayList<>();
for (int i = 0; i < serverCount; ++i) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
joiningServers.add(serverAddress.get(i));
}
for (int i = 0; i < serverCount; ++i) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
}
for (int i = 0; i < serverCount; ++i) {
@@ -189,9 +175,10 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
Map<Integer, String> oldServerAddress = new HashMap<>(serverAddress);
List<String> newServers = new ArrayList<>(joiningServers);
config = updateExistingQuorumConfig(Arrays.asList(3, 4), new ArrayList<Integer>());
- newServers.add(serverAddress.get(3)); newServers.add(serverAddress.get(4));
+ newServers.add(serverAddress.get(3));
+ newServers.add(serverAddress.get(4));
serverCount = serverAddress.size();
- Assert.assertEquals("Server count should be 5 after config update.", serverCount, 5);
+ assertEquals("Server count should be 5 after config update.", serverCount, 5);
// We are adding two new servers to the ensemble. These two servers should have the config which includes
// all five servers (the old three servers, plus the two servers added). The old three servers should only
@@ -199,12 +186,9 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
// peers.
mt = Arrays.copyOf(mt, mt.length + 2);
for (int i = 3; i < 5; ++i) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
verifyQuorumConfig(i, newServers, null);
verifyQuorumMembers(mt[i]);
}
@@ -243,18 +227,16 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
}
private void verifyQuorumMembers(QuorumPeerTestBase.MainThread mt, Set<String> expectedConfigs) {
- Map<Long, QuorumPeer.QuorumServer> members =
- mt.getQuorumPeer().getQuorumVerifier().getAllMembers();
+ Map<Long, QuorumPeer.QuorumServer> members = mt.getQuorumPeer().getQuorumVerifier().getAllMembers();
- Assert.assertTrue("Quorum member should not change.",
- members.size() == expectedConfigs.size());
+ assertTrue("Quorum member should not change.", members.size() == expectedConfigs.size());
for (QuorumPeer.QuorumServer qs : members.values()) {
String actualConfig = qs.toString();
- Assert.assertTrue("Unexpected config " + actualConfig + " found!",
- expectedConfigs.contains(actualConfig));
+ assertTrue("Unexpected config " + actualConfig + " found!", expectedConfigs.contains(actualConfig));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java
index 08dff63fb..97aa763ef 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -22,12 +22,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.mockito.ArgumentMatchers.eq;
-
import java.net.InetSocketAddress;
-
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.junit.Test;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java
index 7bfe4bdc0..7fc2f423e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,46 +18,45 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import javax.security.sasl.SaslException;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.proto.CreateRequest;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.ByteBufferInputStream;
import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.test.QuorumBase;
-import org.apache.zookeeper.test.DisconnectableZooKeeper;
-
public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SessionUpgradeQuorumTest.class);
public static final int CONNECTION_TIMEOUT = ClientBase.CONNECTION_TIMEOUT;
public static final int SERVER_COUNT = 3;
- private MainThread mt[];
- private int clientPorts[];
- private TestQPMainDropSessionUpgrading qpMain[];
+ private MainThread[] mt;
+ private int[] clientPorts;
+ private TestQPMainDropSessionUpgrading[] qpMain;
@Before
public void setUp() throws Exception {
@@ -70,9 +69,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- sb.append("server.").append(i).append("=127.0.0.1:")
- .append(PortAssignment.unique()).append(":")
- .append(PortAssignment.unique()).append("\n");
+ sb.append("server.").append(i).append("=127.0.0.1:").append(PortAssignment.unique()).append(":").append(PortAssignment.unique()).append("\n");
}
sb.append("localSessionsEnabled=true\n");
sb.append("localSessionsUpgradingEnabled=true\n");
@@ -93,9 +90,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
}
@@ -126,8 +121,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
// create a client, and create an ephemeral node to trigger the
// upgrading process
final String node = "/node-1";
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[followerA],
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[followerA], ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
@@ -136,12 +130,11 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
// should fail because of the injection
try {
- zk.create(node, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- Assert.fail("expect to failed to upgrade session due to the " +
- "TestQPMainDropSessionUpgrading is being used");
+ zk.create(node, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ fail("expect to failed to upgrade session due to the "
+ + "TestQPMainDropSessionUpgrading is being used");
} catch (KeeperException e) {
- LOG.info("KeeperException when create ephemeral node, {}", e);
+ LOG.info("KeeperException when create ephemeral node.", e);
}
// force to take snapshot
@@ -155,7 +148,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
mt[i].shutdown();
}
- ArrayList<States> waitStates =new ArrayList<States>();
+ ArrayList<States> waitStates = new ArrayList<States>();
waitStates.add(States.CONNECTING);
waitStates.add(States.CLOSED);
waitForOne(zk, waitStates);
@@ -167,42 +160,36 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
// check global session not exist on follower A
for (int i = 0; i < SERVER_COUNT; i++) {
- ConcurrentHashMap<Long, Integer> sessions =
- mt[i].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
- Assert.assertFalse("server " + i + " should not have global " +
- "session " + sessionId, sessions.containsKey(sessionId));
+ ConcurrentHashMap<Long, Integer> sessions = mt[i].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
+ assertFalse(
+ "server " + i + " should not have global " + "session " + sessionId,
+ sessions.containsKey(sessionId));
}
zk.close();
}
@Test
- public void testOnlyUpgradeSessionOnce()
- throws IOException, InterruptedException, KeeperException {
+ public void testOnlyUpgradeSessionOnce() throws IOException, InterruptedException, KeeperException {
// create a client, and create an ephemeral node to trigger the
// upgrading process
final String node = "/node-1";
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[0],
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[0], ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
long sessionId = zk.getSessionId();
- QuorumZooKeeperServer server =
- (QuorumZooKeeperServer) mt[0].main.quorumPeer.getActiveServer();
+ QuorumZooKeeperServer server = (QuorumZooKeeperServer) mt[0].main.quorumPeer.getActiveServer();
Request create1 = createEphemeralRequest("/data-1", sessionId);
Request create2 = createEphemeralRequest("/data-2", sessionId);
- Assert.assertNotNull("failed to upgrade on a ephemeral create",
- server.checkUpgradeSession(create1));
- Assert.assertNull("tried to upgrade again", server.checkUpgradeSession(create2));
+ assertNotNull("failed to upgrade on a ephemeral create", server.checkUpgradeSession(create1));
+ assertNull("tried to upgrade again", server.checkUpgradeSession(create2));
// clean al the setups and close the zk
zk.close();
@@ -221,15 +208,12 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
return new QuorumPeer() {
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(
- logFactory, this, this.getZkDb())) {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
- protected void request(Request request)
- throws IOException {
+ protected void request(Request request) throws IOException {
if (!shouldDrop) {
super.request(request);
return;
@@ -241,20 +225,18 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
return;
}
- if (request.type == ZooDefs.OpCode.create &&
- request.cnxn != null) {
+ if (request.type == ZooDefs.OpCode.create && request.cnxn != null) {
CreateRequest createRequest = new CreateRequest();
request.request.rewind();
- ByteBufferInputStream.byteBuffer2Record(
- request.request, createRequest);
+ ByteBufferInputStream.byteBuffer2Record(request.request, createRequest);
request.request.rewind();
try {
- CreateMode createMode =
- CreateMode.fromFlag(createRequest.getFlags());
+ CreateMode createMode = CreateMode.fromFlag(createRequest.getFlags());
if (createMode.isEphemeral()) {
request.cnxn.sendCloseSession();
}
- } catch (KeeperException e) {}
+ } catch (KeeperException e) {
+ }
return;
}
@@ -264,6 +246,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
}
};
}
+
}
private void waitForOne(ZooKeeper zk, ArrayList<States> states) throws InterruptedException {
@@ -280,13 +263,10 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
private Request createEphemeralRequest(String path, long sessionId) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- CreateRequest createRequest = new CreateRequest(path,
- "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL.toFlag());
+ CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
- return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb,
- new ArrayList<Id>());
+ return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<Id>());
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java
index 82b959a14..a4fcd8293 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -19,28 +19,28 @@
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.client.FourLetterWordMain;
+import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Test;
public class StandaloneDisabledTest extends QuorumPeerTestBase {
private final int NUM_SERVERS = 5;
- private MainThread peers[];
- private ZooKeeper zkHandles[];
- private ZooKeeperAdmin zkAdminHandles[];
- private int clientPorts[];
+ private MainThread[] peers;
+ private ZooKeeper[] zkHandles;
+ private ZooKeeperAdmin[] zkAdminHandles;
+ private int[] clientPorts;
private final int leaderId = 0;
private final int follower1 = 1;
private final int follower2 = 2;
@@ -60,14 +60,13 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
//start one server
startServer(leaderId, serverStrings.get(leaderId) + "\n");
ReconfigTest.testServerHasConfig(zkHandles[leaderId], null, null);
- LOG.info("Initial Configuration:\n"
- + new String(zkHandles[leaderId].getConfig(this, new Stat())));
+ LOG.info("Initial Configuration:\n" + new String(zkHandles[leaderId].getConfig(this, new Stat())));
//start and add 2 followers
startFollowers();
testReconfig(leaderId, true, reconfigServers);
LOG.info("Configuration after adding 2 followers:\n"
- + new String(zkHandles[leaderId].getConfig(this, new Stat())));
+ + new String(zkHandles[leaderId].getConfig(this, new Stat())));
//shutdown leader- quorum should still exist
shutDownServer(leaderId);
@@ -79,8 +78,9 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
reconfigServers.add(Integer.toString(follower2));
try {
ReconfigTest.reconfig(zkAdminHandles[follower1], null, reconfigServers, null, -1);
- Assert.fail("reconfig completed successfully even though there is no quorum up in new config!");
- } catch (KeeperException.NewConfigNoQuorum e) { }
+ fail("reconfig completed successfully even though there is no quorum up in new config!");
+ } catch (KeeperException.NewConfigNoQuorum e) {
+ }
//reconfigure out leader and follower 1. Remaining follower
//2 should elect itself as leader and run by itself
@@ -88,8 +88,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
reconfigServers.add(Integer.toString(leaderId));
reconfigServers.add(Integer.toString(follower1));
testReconfig(follower2, false, reconfigServers);
- LOG.info("Configuration after removing leader and follower 1:\n"
- + new String(zkHandles[follower2].getConfig(this, new Stat())));
+ LOG.info("Configuration after removing leader and follower 1:\n" + new String(zkHandles[follower2].getConfig(this, new Stat())));
// Kill server 1 to avoid it interferences with FLE of the quorum {2, 3, 4}.
shutDownServer(follower1);
@@ -99,11 +98,11 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
reconfigServers.add(Integer.toString(follower2));
try {
zkAdminHandles[follower2].reconfigure(null, reconfigServers, null, -1, new Stat());
- Assert.fail("reconfig completed successfully even though there is no quorum up in new config!");
+ fail("reconfig completed successfully even though there is no quorum up in new config!");
} catch (KeeperException.BadArgumentsException e) {
// This is expected.
} catch (Exception e) {
- Assert.fail("Should have been BadArgumentsException!");
+ fail("Should have been BadArgumentsException!");
}
//Add two participants and change them to observers to check
@@ -113,7 +112,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
testReconfig(follower2, true, reconfigServers); //add partcipants
testReconfig(follower2, true, observerStrings); //change to observers
LOG.info("Configuration after adding two observers:\n"
- + new String(zkHandles[follower2].getConfig(this, new Stat())));
+ + new String(zkHandles[follower2].getConfig(this, new Stat())));
shutDownData();
}
@@ -131,8 +130,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
clientPorts = new int[NUM_SERVERS];
serverStrings = buildServerStrings();
reconfigServers = new ArrayList<String>();
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
/**
@@ -155,11 +153,10 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
private ArrayList<String> buildServerStrings() {
ArrayList<String> serverStrings = new ArrayList<String>();
- for(int i = 0; i < NUM_SERVERS; i++) {
+ for (int i = 0; i < NUM_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- String server = "server." + i + "=localhost:" + PortAssignment.unique()
- +":"+PortAssignment.unique() + ":participant;"
- + "localhost:" + clientPorts[i];
+ String server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;"
+ + "localhost:" + clientPorts[i];
serverStrings.add(server);
}
return serverStrings;
@@ -173,16 +170,15 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
private void startServer(int id, String config) throws Exception {
peers[id] = new MainThread(id, clientPorts[id], config);
peers[id].start();
- Assert.assertTrue("Server " + id + " is not up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[id], CONNECTION_TIMEOUT));
- Assert.assertTrue("Error- Server started in Standalone Mode!",
- peers[id].isQuorumPeerRunning());
+ assertTrue(
+ "Server " + id + " is not up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[id], CONNECTION_TIMEOUT));
+ assertTrue("Error- Server started in Standalone Mode!", peers[id].isQuorumPeerRunning());
zkHandles[id] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[id]);
zkAdminHandles[id] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[id], CONNECTION_TIMEOUT, this);
zkAdminHandles[id].addAuthInfo("digest", "super:test".getBytes());
String statCommandOut = FourLetterWordMain.send4LetterWord("127.0.0.1", clientPorts[id], "stat");
- LOG.info(String.format("Started server id %d with config:\n%s\nStat output:\n%s",
- id, config, statCommandOut));
+ LOG.info(String.format("Started server id %d with config:\n%s\nStat output:\n%s", id, config, statCommandOut));
}
/**
@@ -203,15 +199,18 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
*/
private void startFollowers() throws Exception {
reconfigServers.clear();
- for(int i = 1; i <= 2; i++) {
- String config = serverStrings.get(leaderId) + "\n"
- + serverStrings.get(i) + "\n"
- + serverStrings.get(i % 2 + 1) + "\n";
+ for (int i = 1; i <= 2; i++) {
+ String config = serverStrings.get(leaderId)
+ + "\n"
+ + serverStrings.get(i)
+ + "\n"
+ + serverStrings.get(i % 2 + 1)
+ + "\n";
startServer(i, config);
reconfigServers.add(serverStrings.get(i));
}
}
- /**
+ /**
* Starts servers 1 and 2 as participants,
* adds them to the list to be reconfigured
* into the ensemble, and adds an observer
@@ -220,9 +219,8 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
*/
private void startObservers(ArrayList<String> observerStrings) throws Exception {
reconfigServers.clear();
- for(int i = observer1; i <= observer2; i++) {
- String config = serverStrings.get(follower2) + "\n"
- + serverStrings.get(i) + "\n";
+ for (int i = observer1; i <= observer2; i++) {
+ String config = serverStrings.get(follower2) + "\n" + serverStrings.get(i) + "\n";
startServer(i, config);
reconfigServers.add(serverStrings.get(i));
observerStrings.add(serverStrings.get(i).replace("participant", "observer"));
@@ -234,8 +232,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
* the given servers. Tests appropriately to make sure the
* reconfig succeeded.
*/
- private void testReconfig(int id, boolean adding,
- ArrayList<String> servers) throws Exception {
+ private void testReconfig(int id, boolean adding, ArrayList<String> servers) throws Exception {
if (adding) {
ReconfigTest.reconfig(zkAdminHandles[id], servers, null, null, -1);
for (String server : servers) {
@@ -250,18 +247,19 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
}
- /**
- * Ensure observer cannot start by itself
- **/
+ /**
+ * Ensure observer cannot start by itself
+ **/
@Test
public void startObserver() throws Exception {
int clientPort = PortAssignment.unique();
- String config = "server." + observer1 + "=localhost:"+ PortAssignment.unique()
- + ":" + clientPort + ":observer;"
- + "localhost:" + PortAssignment.unique();
+ String config = "server." + observer1 + "=localhost:" + PortAssignment.unique() + ":" + clientPort
+ + ":observer;" + "localhost:" + PortAssignment.unique();
MainThread observer = new MainThread(observer1, clientPort, config);
observer.start();
- Assert.assertFalse("Observer was able to start by itself!",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertFalse(
+ "Observer was able to start by itself!",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java
index eccb6b184..7a46bac05 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,14 @@
package org.apache.zookeeper.server.quorum;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.zookeeper.server.ServerCnxn;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ServerStats;
@@ -27,17 +35,8 @@ import org.apache.zookeeper.server.command.StatCommand;
import org.junit.Before;
import org.junit.Test;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class StatCommandTest {
+
private StringWriter outputWriter;
private StatCommand statCommand;
private ServerStats.Provider providerMock;
@@ -102,4 +101,5 @@ public class StatCommandTest {
assertThat(output, containsString("Zookeeper version:"));
assertThat(output, containsString("Node count:"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java
index 0c20c5887..850c4d81f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,24 +18,23 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.server.ServerCnxn;
-import org.apache.zookeeper.server.ServerStats;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.apache.zookeeper.server.command.StatResetCommand;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
import static org.apache.zookeeper.server.command.AbstractFourLetterCommand.ZK_NOT_SERVING;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import org.apache.zookeeper.server.ServerCnxn;
+import org.apache.zookeeper.server.ServerStats;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.command.StatResetCommand;
+import org.junit.Before;
+import org.junit.Test;
public class StatResetCommandTest {
+
private StatResetCommand statResetCommand;
private StringWriter outputWriter;
private ZooKeeperServer zks;
@@ -108,4 +107,5 @@ public class StatResetCommandTest {
verify(serverStats, times(1)).reset();
verify(bufferStats, times(1)).reset();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java
index 843dfabfb..c00362219 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,26 +18,30 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.server.*;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.ByteBuffer;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.server.RequestProcessor;
+import org.apache.zookeeper.server.SyncRequestProcessor;
+import org.apache.zookeeper.server.ZKDatabase;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.junit.Before;
+import org.junit.Test;
public class SyncRequestProcessorMetricTest {
+
ZooKeeperServer zks;
RequestProcessor nextProcessor;
CountDownLatch allRequestsFlushed;
@@ -46,7 +50,7 @@ public class SyncRequestProcessorMetricTest {
public void setup() throws Exception {
ZKDatabase db = mock(ZKDatabase.class);
when(db.append(any(Request.class))).thenReturn(true);
- doAnswer(invocation->{
+ doAnswer(invocation -> {
Thread.sleep(100);
return null;
}).when(db).commit();
@@ -61,19 +65,18 @@ public class SyncRequestProcessorMetricTest {
}
private Request createRquest(long sessionId, int xid) {
- return new Request(null, sessionId, xid, ZooDefs.OpCode.setData,
- ByteBuffer.wrap(new byte[10]), null);
+ return new Request(null, sessionId, xid, ZooDefs.OpCode.setData, ByteBuffer.wrap(new byte[10]), null);
}
@Test
- public void testSyncProcessorMetrics() throws Exception{
+ public void testSyncProcessorMetrics() throws Exception {
SyncRequestProcessor syncProcessor = new SyncRequestProcessor(zks, nextProcessor);
- for (int i=0; i<500; i++) {
+ for (int i = 0; i < 500; i++) {
syncProcessor.processRequest(createRquest(1, i));
}
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(500L, values.get("sync_processor_request_queued"));
+ assertEquals(500L, values.get("sync_processor_request_queued"));
allRequestsFlushed = new CountDownLatch(500);
syncProcessor.start();
@@ -82,23 +85,24 @@ public class SyncRequestProcessorMetricTest {
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(501L, values.get("cnt_sync_processor_queue_size"));
- Assert.assertEquals(500L, values.get("max_sync_processor_queue_size"));
- Assert.assertEquals(0L, values.get("min_sync_processor_queue_size"));
+ assertEquals(501L, values.get("cnt_sync_processor_queue_size"));
+ assertEquals(500L, values.get("max_sync_processor_queue_size"));
+ assertEquals(0L, values.get("min_sync_processor_queue_size"));
- Assert.assertEquals(500L, values.get("cnt_sync_processor_queue_time_ms"));
- Assert.assertThat((long)values.get("max_sync_processor_queue_time_ms"), greaterThan(0L));
+ assertEquals(500L, values.get("cnt_sync_processor_queue_time_ms"));
+ assertThat((long) values.get("max_sync_processor_queue_time_ms"), greaterThan(0L));
- Assert.assertEquals(500L, values.get("cnt_sync_processor_queue_and_flush_time_ms"));
- Assert.assertThat((long)values.get("max_sync_processor_queue_and_flush_time_ms"), greaterThan(0L));
+ assertEquals(500L, values.get("cnt_sync_processor_queue_and_flush_time_ms"));
+ assertThat((long) values.get("max_sync_processor_queue_and_flush_time_ms"), greaterThan(0L));
- Assert.assertEquals(500L, values.get("cnt_sync_process_time"));
- Assert.assertThat((long)values.get("max_sync_process_time"), greaterThan(0L));
+ assertEquals(500L, values.get("cnt_sync_process_time"));
+ assertThat((long) values.get("max_sync_process_time"), greaterThan(0L));
- Assert.assertEquals(500L, values.get("max_sync_processor_batch_size"));
- Assert.assertEquals(1L, values.get("cnt_sync_processor_queue_flush_time_ms"));
- Assert.assertThat((long)values.get("max_sync_processor_queue_flush_time_ms"), greaterThanOrEqualTo(100L));
+ assertEquals(500L, values.get("max_sync_processor_batch_size"));
+ assertEquals(1L, values.get("cnt_sync_processor_queue_flush_time_ms"));
+ assertThat((long) values.get("max_sync_processor_queue_flush_time_ms"), greaterThanOrEqualTo(100L));
syncProcessor.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
index e9267b9ef..d02c11438 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,8 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
@@ -32,7 +36,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
@@ -45,7 +48,6 @@ import org.apache.zookeeper.test.ClientBase;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -61,14 +63,14 @@ import org.slf4j.LoggerFactory;
*/
@RunWith(Parameterized.class)
public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory.getLogger(
- UnifiedServerSocketModeDetectionTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(UnifiedServerSocketModeDetectionTest.class);
@Parameterized.Parameters
public static Collection<Object[]> params() {
ArrayList<Object[]> result = new ArrayList<>();
- result.add(new Object[] { true });
- result.add(new Object[] { false });
+ result.add(new Object[]{true});
+ result.add(new Object[]{false});
return result;
}
@@ -88,11 +90,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
public static void setUpClass() throws Exception {
Security.addProvider(new BouncyCastleProvider());
tempDir = ClientBase.createEmptyTestDir();
- x509TestContext = X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStoreKeyType(X509KeyType.EC)
- .setTrustStoreKeyType(X509KeyType.EC)
- .build();
+ x509TestContext = X509TestContext.newBuilder().setTempDir(tempDir).setKeyStoreKeyType(X509KeyType.EC).setTrustStoreKeyType(X509KeyType.EC).build();
}
@AfterClass
@@ -157,7 +155,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
} else {
clientSocket = new Socket();
clientSocket.connect(localServerAddress);
- clientSocket.getOutputStream().write(new byte[] { 1, 2, 3, 4, 5 });
+ clientSocket.getOutputStream().write(new byte[]{1, 2, 3, 4, 5});
}
serverSideSocket = acceptFuture.get();
}
@@ -177,55 +175,55 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetInetAddress() {
serverSideSocket.getInetAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetLocalAddress() {
serverSideSocket.getLocalAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetPort() {
serverSideSocket.getPort();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetLocalPort() {
serverSideSocket.getLocalPort();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetRemoteSocketAddress() {
serverSideSocket.getRemoteSocketAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetLocalSocketAddress() {
serverSideSocket.getLocalSocketAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetInputStream() throws IOException {
serverSideSocket.getInputStream();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetOutputStream() throws IOException {
serverSideSocket.getOutputStream();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetTcpNoDelay() throws IOException {
serverSideSocket.getTcpNoDelay();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -233,14 +231,14 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
boolean tcpNoDelay = serverSideSocket.getTcpNoDelay();
tcpNoDelay = !tcpNoDelay;
serverSideSocket.setTcpNoDelay(tcpNoDelay);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(tcpNoDelay, serverSideSocket.getTcpNoDelay());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(tcpNoDelay, serverSideSocket.getTcpNoDelay());
}
@Test
public void testGetSoLinger() throws IOException {
serverSideSocket.getSoLinger();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -249,20 +247,20 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
if (soLinger == -1) {
// enable it if disabled
serverSideSocket.setSoLinger(true, 1);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(1, serverSideSocket.getSoLinger());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(1, serverSideSocket.getSoLinger());
} else {
// disable it if enabled
serverSideSocket.setSoLinger(false, -1);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(-1, serverSideSocket.getSoLinger());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(-1, serverSideSocket.getSoLinger());
}
}
@Test
public void testGetSoTimeout() throws IOException {
serverSideSocket.getSoTimeout();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -270,20 +268,20 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
int timeout = serverSideSocket.getSoTimeout();
timeout = timeout + 10;
serverSideSocket.setSoTimeout(timeout);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(timeout, serverSideSocket.getSoTimeout());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(timeout, serverSideSocket.getSoTimeout());
}
@Test
public void testGetSendBufferSize() throws IOException {
serverSideSocket.getSendBufferSize();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testSetSendBufferSize() throws IOException {
serverSideSocket.setSendBufferSize(serverSideSocket.getSendBufferSize() + 1024);
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
// Note: the new buffer size is a hint and socket implementation
// is free to ignore it, so we don't verify that we get back the
// same value.
@@ -293,13 +291,13 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetReceiveBufferSize() throws IOException {
serverSideSocket.getReceiveBufferSize();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testSetReceiveBufferSize() throws IOException {
serverSideSocket.setReceiveBufferSize(serverSideSocket.getReceiveBufferSize() + 1024);
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
// Note: the new buffer size is a hint and socket implementation
// is free to ignore it, so we don't verify that we get back the
// same value.
@@ -309,7 +307,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetKeepAlive() throws IOException {
serverSideSocket.getKeepAlive();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -317,20 +315,20 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
boolean keepAlive = serverSideSocket.getKeepAlive();
keepAlive = !keepAlive;
serverSideSocket.setKeepAlive(keepAlive);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(keepAlive, serverSideSocket.getKeepAlive());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(keepAlive, serverSideSocket.getKeepAlive());
}
@Test
public void testGetTrafficClass() throws IOException {
serverSideSocket.getTrafficClass();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testSetTrafficClass() throws IOException {
serverSideSocket.setTrafficClass(SocketOptions.IP_TOS);
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
// Note: according to the Socket javadocs, setTrafficClass() may be
// ignored by socket implementations, so we don't check that the value
// we set is returned.
@@ -339,7 +337,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetReuseAddress() throws IOException {
serverSideSocket.getReuseAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -347,59 +345,60 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
boolean reuseAddress = serverSideSocket.getReuseAddress();
reuseAddress = !reuseAddress;
serverSideSocket.setReuseAddress(reuseAddress);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(reuseAddress, serverSideSocket.getReuseAddress());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(reuseAddress, serverSideSocket.getReuseAddress());
}
@Test
public void testClose() throws IOException {
serverSideSocket.close();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testShutdownInput() throws IOException {
serverSideSocket.shutdownInput();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testShutdownOutput() throws IOException {
serverSideSocket.shutdownOutput();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsConnected() {
serverSideSocket.isConnected();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsBound() {
serverSideSocket.isBound();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsClosed() {
serverSideSocket.isClosed();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsInputShutdown() throws IOException {
serverSideSocket.isInputShutdown();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
serverSideSocket.shutdownInput();
- Assert.assertTrue(serverSideSocket.isInputShutdown());
+ assertTrue(serverSideSocket.isInputShutdown());
}
@Test
public void testIsOutputShutdown() throws IOException {
serverSideSocket.isOutputShutdown();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
serverSideSocket.shutdownOutput();
- Assert.assertTrue(serverSideSocket.isOutputShutdown());
+ assertTrue(serverSideSocket.isOutputShutdown());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java
index b74fcda98..7e4fa69ad 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,8 +15,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ConnectException;
@@ -32,11 +39,9 @@ import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSocket;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.common.BaseX509ParameterizedTestCase;
import org.apache.zookeeper.common.ClientX509Util;
@@ -46,7 +51,6 @@ import org.apache.zookeeper.common.X509KeyType;
import org.apache.zookeeper.common.X509TestContext;
import org.apache.zookeeper.common.X509Util;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -61,13 +65,8 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
int paramIndex = 0;
for (X509KeyType caKeyType : X509KeyType.values()) {
for (X509KeyType certKeyType : X509KeyType.values()) {
- for (Boolean hostnameVerification : new Boolean[] { true, false }) {
- result.add(new Object[]{
- caKeyType,
- certKeyType,
- hostnameVerification,
- paramIndex++
- });
+ for (Boolean hostnameVerification : new Boolean[]{true, false}) {
+ result.add(new Object[]{caKeyType, certKeyType, hostnameVerification, paramIndex++});
}
}
}
@@ -86,18 +85,10 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
private boolean handshakeCompleted = false;
public UnifiedServerSocketTest(
- final X509KeyType caKeyType,
- final X509KeyType certKeyType,
- final Boolean hostnameVerification,
- final Integer paramIndex) {
+ final X509KeyType caKeyType, final X509KeyType certKeyType, final Boolean hostnameVerification, final Integer paramIndex) {
super(paramIndex, () -> {
try {
- return X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStoreKeyType(certKeyType)
- .setTrustStoreKeyType(caKeyType)
- .setHostnameVerification(hostnameVerification)
- .build();
+ return X509TestContext.newBuilder().setTempDir(tempDir).setKeyStoreKeyType(certKeyType).setTrustStoreKeyType(caKeyType).setHostnameVerification(hostnameVerification).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -138,15 +129,13 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
}
private static final class UnifiedServerThread extends Thread {
+
private final byte[] dataToClient;
private List<byte[]> dataFromClients;
private ExecutorService workerPool;
private UnifiedServerSocket serverSocket;
- UnifiedServerThread(X509Util x509Util,
- InetSocketAddress bindAddress,
- boolean allowInsecureConnection,
- byte[] dataToClient) throws IOException {
+ UnifiedServerThread(X509Util x509Util, InetSocketAddress bindAddress, boolean allowInsecureConnection, byte[] dataToClient) throws IOException {
this.dataToClient = dataToClient;
dataFromClients = new ArrayList<>();
workerPool = Executors.newCachedThreadPool();
@@ -175,9 +164,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
int bytesRead = unifiedSocket.getInputStream().read(buf, 0, 1024);
// Make sure the settings applied above before the socket was potentially upgraded to
// TLS still apply.
- Assert.assertEquals(tcpNoDelay, unifiedSocket.getTcpNoDelay());
- Assert.assertEquals(TIMEOUT, unifiedSocket.getSoTimeout());
- Assert.assertEquals(keepAlive, unifiedSocket.getKeepAlive());
+ assertEquals(tcpNoDelay, unifiedSocket.getTcpNoDelay());
+ assertEquals(TIMEOUT, unifiedSocket.getSoTimeout());
+ assertEquals(keepAlive, unifiedSocket.getKeepAlive());
if (bytesRead > 0) {
byte[] dataFromClient = new byte[bytesRead];
System.arraycopy(buf, 0, dataFromClient, 0, bytesRead);
@@ -216,6 +205,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
synchronized boolean receivedAnyDataFromClient() {
return !dataFromClients.isEmpty();
}
+
}
private SSLSocket connectWithSSL() throws IOException, X509Exception, InterruptedException {
@@ -245,7 +235,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
retries++;
}
- Assert.assertNotNull("Failed to connect to server with SSL", sslSocket);
+ assertNotNull("Failed to connect to server with SSL", sslSocket);
return sslSocket;
}
@@ -266,7 +256,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
}
retries++;
}
- Assert.assertNotNull("Failed to connect to server without SSL", socket);
+ assertNotNull("Failed to connect to server without SSL", socket);
return socket;
}
@@ -280,8 +270,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithSSLToNonStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
Socket sslSocket = connectWithSSL();
@@ -290,16 +279,16 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
sslSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = sslSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(sslSocket);
serverThread.shutdown(TIMEOUT);
@@ -311,8 +300,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithSSLToStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
Socket sslSocket = connectWithSSL();
@@ -321,17 +309,17 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
sslSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = sslSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(sslSocket);
serverThread.shutdown(TIMEOUT);
@@ -343,8 +331,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithoutSSLToNonStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
Socket socket = connectWithoutSSL();
@@ -353,9 +340,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
socket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = socket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(socket);
serverThread.shutdown(TIMEOUT);
@@ -370,8 +357,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithoutSSLToNonStrictServerPartialWrite() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
Socket socket = connectWithoutSSL();
@@ -386,9 +372,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
socket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = socket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(socket);
serverThread.shutdown(TIMEOUT);
@@ -400,8 +386,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithoutSSLToStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
Socket socket = connectWithoutSSL();
@@ -410,7 +395,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
byte[] buf = new byte[DATA_TO_CLIENT.length];
try {
int bytesRead = socket.getInputStream().read(buf, 0, buf.length);
- if(bytesRead == -1) {
+ if (bytesRead == -1) {
// Using the NioSocketImpl after JDK 13, the expected behaviour on the client side
// is to reach the end of the stream (bytesRead == -1), without a socket exception.
return;
@@ -424,10 +409,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
// independently of the client socket implementation details, we always make sure the
// server didn't receive any data during the test
- Assert.assertFalse("The strict server accepted connection without SSL.",
- serverThread.receivedAnyDataFromClient());
+ assertFalse("The strict server accepted connection without SSL.", serverThread.receivedAnyDataFromClient());
}
- Assert.fail("Expected server to hang up the connection. Read from server succeeded unexpectedly.");
+ fail("Expected server to hang up the connection. Read from server succeeded unexpectedly.");
}
/**
@@ -446,8 +430,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
Socket badClientSocket = null;
Socket clientSocket = null;
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -458,12 +441,12 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
clientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = clientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
synchronized (handshakeCompletedLock) {
- Assert.assertFalse(handshakeCompleted);
+ assertFalse(handshakeCompleted);
}
secureClientSocket = connectWithSSL();
@@ -471,15 +454,15 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
buf = new byte[DATA_TO_CLIENT.length];
bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
} finally {
forceClose(badClientSocket);
@@ -497,8 +480,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
public void testTLSDetectionNonBlockingStrictServerIdleClient() throws Exception {
Socket badClientSocket = null;
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -509,16 +491,16 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(badClientSocket);
forceClose(secureClientSocket);
@@ -534,8 +516,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
public void testTLSDetectionNonBlockingNonStrictServerDisconnectedClient() throws Exception {
Socket clientSocket = null;
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -547,12 +528,12 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
clientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = clientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
synchronized (handshakeCompletedLock) {
- Assert.assertFalse(handshakeCompleted);
+ assertFalse(handshakeCompleted);
}
secureClientSocket = connectWithSSL();
@@ -560,15 +541,15 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
buf = new byte[DATA_TO_CLIENT.length];
bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
} finally {
forceClose(clientSocket);
@@ -584,8 +565,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
@Test
public void testTLSDetectionNonBlockingStrictServerDisconnectedClient() throws Exception {
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -597,19 +577,20 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(secureClientSocket);
serverThread.shutdown(TIMEOUT);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java
index 4eebcf343..cdc3b8304 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -17,15 +17,10 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -40,29 +35,32 @@ import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
+import java.util.List;
import java.util.Random;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.zookeeper.MockPacket;
+import org.apache.zookeeper.ZKParameterized;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.proto.ConnectRequest;
import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.proto.SetWatches;
import org.apache.zookeeper.server.MockNIOServerCnxn;
+import org.apache.zookeeper.server.MockSelectorThread;
import org.apache.zookeeper.server.NIOServerCnxn;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
-import org.apache.zookeeper.server.MockSelectorThread;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.ZKParameterized;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
@@ -75,8 +73,7 @@ import org.slf4j.LoggerFactory;
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class WatchLeakTest {
- protected static final Logger LOG = LoggerFactory
- .getLogger(WatchLeakTest.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(WatchLeakTest.class);
final long SESSION_ID = 0xBABEL;
@@ -93,9 +90,7 @@ public class WatchLeakTest {
@Parameters
public static Collection<Object[]> configs() {
- return Arrays.asList(new Object[][] {
- { false }, { true },
- });
+ return Arrays.asList(new Object[][]{{false}, {true}});
}
/**
@@ -111,8 +106,8 @@ public class WatchLeakTest {
when(selectorThread.addInterestOpsUpdateRequest(any(SelectionKey.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
- SelectionKey sk = (SelectionKey)invocation.getArguments()[0];
- NIOServerCnxn nioSrvCnx = (NIOServerCnxn)sk.attachment();
+ SelectionKey sk = (SelectionKey) invocation.getArguments()[0];
+ NIOServerCnxn nioSrvCnx = (NIOServerCnxn) sk.attachment();
sk.interestOps(nioSrvCnx.getInterestOps());
return true;
}
@@ -137,8 +132,7 @@ public class WatchLeakTest {
// Simulate a socket channel between a client and a follower
final SocketChannel socketChannel = createClientSocketChannel();
// Create the NIOServerCnxn that will handle the client requests
- final MockNIOServerCnxn nioCnxn = new MockNIOServerCnxn(fzks,
- socketChannel, sk, serverCnxnFactory, selectorThread);
+ final MockNIOServerCnxn nioCnxn = new MockNIOServerCnxn(fzks, socketChannel, sk, serverCnxnFactory, selectorThread);
sk.attach(nioCnxn);
// Send the connection request as a client do
nioCnxn.doIO(sk);
@@ -175,6 +169,7 @@ public class WatchLeakTest {
* A follower with no real leader connection
*/
public static class MyFollower extends Follower {
+
/**
* Create a follower with a mocked leader connection
*
@@ -187,6 +182,7 @@ public class WatchLeakTest {
leaderIs = mock(InputArchive.class);
bufferedOutput = mock(BufferedOutputStream.class);
}
+
}
/**
@@ -252,8 +248,7 @@ public class WatchLeakTest {
dataWatches.add("/");
List<String> existWatches = Collections.emptyList();
List<String> childWatches = Collections.emptyList();
- SetWatches sw = new SetWatches(1L, dataWatches, existWatches,
- childWatches);
+ SetWatches sw = new SetWatches(1L, dataWatches, existWatches, childWatches);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setWatches);
h.setXid(-8);
@@ -265,7 +260,7 @@ public class WatchLeakTest {
* This is the secret that we use to generate passwords, for the moment it
* is more of a sanity check.
*/
- static final private long superSecret = 0XB3415C00L;
+ private static final long superSecret = 0XB3415C00L;
/**
* Create a connection request
@@ -274,7 +269,7 @@ public class WatchLeakTest {
*/
private ByteBuffer createConnRequest() {
Random r = new Random(SESSION_ID ^ superSecret);
- byte p[] = new byte[16];
+ byte[] p = new byte[16];
r.nextBytes(p);
ConnectRequest conReq = new ConnectRequest(0, 1L, 30000, SESSION_ID, p);
MockPacket packet = new MockPacket(null, null, conReq, null, null, false);
@@ -299,8 +294,7 @@ public class WatchLeakTest {
// Send watches packet to server connection
final ByteBuffer connRequest = createConnRequest();
final ByteBuffer watchesMessage = createWatchesMessage();
- final ByteBuffer request = ByteBuffer.allocate(connRequest.limit()
- + watchesMessage.limit());
+ final ByteBuffer request = ByteBuffer.allocate(connRequest.limit() + watchesMessage.limit());
request.put(connRequest);
request.put(watchesMessage);
@@ -355,8 +349,7 @@ public class WatchLeakTest {
dos.writeLong(SESSION_ID);
dos.writeInt(3000);
dos.close();
- QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1,
- baos.toByteArray(), null);
+ QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1, baos.toByteArray(), null);
return qp;
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
index 1aa0d24f5..037f81f26 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,30 +18,30 @@
package org.apache.zookeeper.server.quorum;
-import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
-import static org.apache.zookeeper.server.quorum.ZabUtils.createMockLeader;
import static org.apache.zookeeper.server.quorum.ZabUtils.MockLeader;
import static org.apache.zookeeper.server.quorum.ZabUtils.createLeader;
-
+import static org.apache.zookeeper.server.quorum.ZabUtils.createMockLeader;
+import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-import java.io.EOFException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
@@ -49,6 +49,7 @@ import org.apache.jute.OutputArchive;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ByteBufferInputStream;
@@ -58,7 +59,6 @@ import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-
import org.apache.zookeeper.server.util.ZxidUtils;
import org.apache.zookeeper.test.TestUtils;
import org.apache.zookeeper.txn.CreateSessionTxn;
@@ -66,8 +66,6 @@ import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.ErrorTxn;
import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -77,8 +75,7 @@ public class Zab1_0Test extends ZKTestCase {
private static final Logger LOG = LoggerFactory.getLogger(Zab1_0Test.class);
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
@Before
public void setUp() {
@@ -86,6 +83,7 @@ public class Zab1_0Test extends ZKTestCase {
}
private static final class LeadThread extends Thread {
+
private final Leader leader;
private LeadThread(Leader leader) {
@@ -103,16 +101,18 @@ public class Zab1_0Test extends ZKTestCase {
leader.shutdown("lead ended");
}
}
+
}
-
- public static final class FollowerMockThread extends Thread {
- private final Leader leader;
- private final long followerSid;
- public long epoch = -1;
- public String msg = null;
- private boolean onlyGetEpochToPropose;
-
- private FollowerMockThread(long followerSid, Leader leader, boolean onlyGetEpochToPropose) {
+
+ public static final class FollowerMockThread extends Thread {
+
+ private final Leader leader;
+ private final long followerSid;
+ public long epoch = -1;
+ public String msg = null;
+ private boolean onlyGetEpochToPropose;
+
+ private FollowerMockThread(long followerSid, Leader leader, boolean onlyGetEpochToPropose) {
this.leader = leader;
this.followerSid = followerSid;
this.onlyGetEpochToPropose = onlyGetEpochToPropose;
@@ -120,21 +120,22 @@ public class Zab1_0Test extends ZKTestCase {
public void run() {
if (onlyGetEpochToPropose) {
- try {
- epoch = leader.getEpochToPropose(followerSid, 0);
- } catch (Exception e) {
- }
- } else {
- try{
- leader.waitForEpochAck(followerSid, new StateSummary(0, 0));
- msg = "FollowerMockThread (id = " + followerSid + ") returned from waitForEpochAck";
- } catch (Exception e) {
- }
+ try {
+ epoch = leader.getEpochToPropose(followerSid, 0);
+ } catch (Exception e) {
+ }
+ } else {
+ try {
+ leader.waitForEpochAck(followerSid, new StateSummary(0, 0));
+ msg = "FollowerMockThread (id = " + followerSid + ") returned from waitForEpochAck";
+ } catch (Exception e) {
+ }
}
- }
+ }
+
}
@Test
- public void testLeaderInConnectingFollowers() throws Exception {
+ public void testLeaderInConnectingFollowers() throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -144,26 +145,26 @@ public class Zab1_0Test extends ZKTestCase {
leader = createLeader(tmpDir, peer);
peer.leader = leader;
peer.setAcceptedEpoch(5);
-
+
FollowerMockThread f1 = new FollowerMockThread(1, leader, true);
FollowerMockThread f2 = new FollowerMockThread(2, leader, true);
f1.start();
f2.start();
-
+
// wait until followers time out in getEpochToPropose - they shouldn't return
// normally because the leader didn't execute getEpochToPropose and so its epoch was not
// accounted for
- f1.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
- f2.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
-
+ f1.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+ f2.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+
// even though followers timed out, their ids are in connectingFollowers, and their
- // epoch were accounted for, so the leader should not block and since it started with
+ // epoch were accounted for, so the leader should not block and since it started with
// accepted epoch = 5 it should now have 6
try {
- long epoch = leader.getEpochToPropose(leader.self.getId(), leader.self.getAcceptedEpoch());
- Assert.assertEquals("leader got wrong epoch from getEpochToPropose", 6, epoch);
- } catch (Exception e){
- Assert.fail("leader timed out in getEpochToPropose");
+ long epoch = leader.getEpochToPropose(leader.self.getId(), leader.self.getAcceptedEpoch());
+ assertEquals("leader got wrong epoch from getEpochToPropose", 6, epoch);
+ } catch (Exception e) {
+ fail("leader timed out in getEpochToPropose");
}
} finally {
if (leader != null) {
@@ -172,23 +173,23 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
+
/**
* In this test, the leader sets the last accepted epoch to 5. The call
- * to getEpochToPropose should set epoch to 6 and wait until another
+ * to getEpochToPropose should set epoch to 6 and wait until another
* follower executes it. If in getEpochToPropose we don't check if
* lastAcceptedEpoch == epoch, then the call from the subsequent
* follower with lastAcceptedEpoch = 6 doesn't change the value
* of epoch, and the test fails. It passes with the fix to predicate.
- *
+ *
* https://issues.apache.org/jira/browse/ZOOKEEPER-1343
- *
- *
+ *
+ *
* @throws Exception
*/
-
+
@Test
- public void testLastAcceptedEpoch() throws Exception {
+ public void testLastAcceptedEpoch() throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -199,20 +200,20 @@ public class Zab1_0Test extends ZKTestCase {
leader = createMockLeader(tmpDir, peer);
peer.leader = leader;
peer.setAcceptedEpoch(5);
- leadThread = new LeadThread(leader);
+ leadThread = new LeadThread(leader);
leadThread.start();
-
- while(((MockLeader) leader).getCurrentEpochToPropose() != 6){
+
+ while (((MockLeader) leader).getCurrentEpochToPropose() != 6) {
Thread.sleep(20);
}
-
+
try {
long epoch = leader.getEpochToPropose(1, 6);
- Assert.assertEquals("New proposed epoch is wrong", 7, epoch);
- } catch (Exception e){
- Assert.fail("Timed out in getEpochToPropose");
+ assertEquals("New proposed epoch is wrong", 7, epoch);
+ } catch (Exception e) {
+ fail("Timed out in getEpochToPropose");
}
-
+
} finally {
if (leader != null) {
leader.shutdown("end of test");
@@ -224,10 +225,9 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
-
+
@Test
- public void testLeaderInElectingFollowers() throws Exception {
+ public void testLeaderInElectingFollowers() throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -235,25 +235,25 @@ public class Zab1_0Test extends ZKTestCase {
try {
QuorumPeer peer = createQuorumPeer(tmpDir);
leader = createLeader(tmpDir, peer);
- peer.leader = leader;
-
+ peer.leader = leader;
+
FollowerMockThread f1 = new FollowerMockThread(1, leader, false);
FollowerMockThread f2 = new FollowerMockThread(2, leader, false);
// things needed for waitForEpochAck to run (usually in leader.lead(), but we're not running leader here)
leader.leaderStateSummary = new StateSummary(leader.self.getCurrentEpoch(), leader.zk.getLastProcessedZxid());
-
+
f1.start();
- f2.start();
-
+ f2.start();
+
// wait until followers time out in waitForEpochAck - they shouldn't return
// normally because the leader didn't execute waitForEpochAck
- f1.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
- f2.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
-
- // make sure that they timed out and didn't return normally
- Assert.assertTrue(f1.msg + " without waiting for leader", f1.msg == null);
- Assert.assertTrue(f2.msg + " without waiting for leader", f2.msg == null);
+ f1.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+ f2.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+
+ // make sure that they timed out and didn't return normally
+ assertTrue(f1.msg + " without waiting for leader", f1.msg == null);
+ assertTrue(f2.msg + " without waiting for leader", f2.msg == null);
} finally {
if (leader != null) {
leader.shutdown("end of test");
@@ -263,39 +263,46 @@ public class Zab1_0Test extends ZKTestCase {
}
static Socket[] getSocketPair() throws IOException {
- ServerSocket ss =
- new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ ServerSocket ss = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
InetSocketAddress endPoint = (InetSocketAddress) ss.getLocalSocketAddress();
Socket s = new Socket(endPoint.getAddress(), endPoint.getPort());
- return new Socket[] { s, ss.accept() };
+ return new Socket[]{s, ss.accept()};
}
static void readPacketSkippingPing(InputArchive ia, QuorumPacket qp) throws IOException {
- while(true) {
+ while (true) {
ia.readRecord(qp, null);
if (qp.getType() != Leader.PING) {
return;
}
}
}
-
- static public interface LeaderConversation {
+
+ public interface LeaderConversation {
+
void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws Exception;
+
}
-
- static public interface PopulatedLeaderConversation {
+
+ public interface PopulatedLeaderConversation {
+
void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l, long zxid) throws Exception;
+
}
-
- static public interface FollowerConversation {
+
+ public interface FollowerConversation {
+
void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception;
+
}
-
- static public interface ObserverConversation {
+
+ public interface ObserverConversation {
+
void converseWithObserver(InputArchive ia, OutputArchive oa, Observer o) throws Exception;
+
}
public void testLeaderConversation(LeaderConversation conversation) throws Exception {
- Socket pair[] = getSocketPair();
+ Socket[] pair = getSocketPair();
Socket leaderSocket = pair[0];
Socket followerSocket = pair[1];
File tmpDir = File.createTempFile("test", "dir", testData);
@@ -310,20 +317,16 @@ public class Zab1_0Test extends ZKTestCase {
leadThread = new LeadThread(leader);
leadThread.start();
- while(leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
+ while (leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
Thread.sleep(20);
}
-
- LearnerHandler lh = new LearnerHandler(leaderSocket,
- new BufferedInputStream(leaderSocket.getInputStream()),
- leader);
+
+ LearnerHandler lh = new LearnerHandler(leaderSocket, new BufferedInputStream(leaderSocket.getInputStream()), leader);
lh.start();
leaderSocket.setSoTimeout(4000);
- InputArchive ia = BinaryInputArchive.getArchive(followerSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket
- .getOutputStream());
+ InputArchive ia = BinaryInputArchive.getArchive(followerSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket.getOutputStream());
conversation.converseWithLeader(ia, oa, leader);
} finally {
@@ -337,9 +340,9 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
+
public void testPopulatedLeaderConversation(PopulatedLeaderConversation conversation, int ops) throws Exception {
- Socket pair[] = getSocketPair();
+ Socket[] pair = getSocketPair();
Socket leaderSocket = pair[0];
Socket followerSocket = pair[1];
File tmpDir = File.createTempFile("test", "dir", testData);
@@ -347,54 +350,49 @@ public class Zab1_0Test extends ZKTestCase {
tmpDir.mkdir();
LeadThread leadThread = null;
Leader leader = null;
- try {
+ try {
// Setup a database with two znodes
FileTxnSnapLog snapLog = new FileTxnSnapLog(tmpDir, tmpDir);
ZKDatabase zkDb = new ZKDatabase(snapLog);
-
- Assert.assertTrue(ops >= 1);
- long zxid = ZxidUtils.makeZxid(1, 0);
- for(int i = 1; i <= ops; i++){
+
+ assertTrue(ops >= 1);
+ long zxid = ZxidUtils.makeZxid(1, 0);
+ for (int i = 1; i <= ops; i++) {
zxid = ZxidUtils.makeZxid(1, i);
- String path = "/foo-"+ i;
- zkDb.processTxn(new TxnHeader(13,1000+i,zxid,30+i,ZooDefs.OpCode.create),
- new CreateTxn(path, "fpjwasalsohere".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
+ String path = "/foo-" + i;
+ zkDb.processTxn(new TxnHeader(13, 1000 + i, zxid, 30
+ + i, ZooDefs.OpCode.create), new CreateTxn(path, "fpjwasalsohere".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("fpjwasalsohere", new String(zkDb.getData(path, stat, null)));
- }
- Assert.assertTrue(zxid > ZxidUtils.makeZxid(1, 0));
-
+ assertEquals("fpjwasalsohere", new String(zkDb.getData(path, stat, null)));
+ }
+ assertTrue(zxid > ZxidUtils.makeZxid(1, 0));
+
// Generate snapshot and close files.
snapLog.save(zkDb.getDataTree(), zkDb.getSessionWithTimeOuts(), false);
snapLog.close();
-
+
QuorumPeer peer = createQuorumPeer(tmpDir);
-
+
leader = createLeader(tmpDir, peer);
peer.leader = leader;
-
+
// Set the last accepted epoch and current epochs to be 1
peer.setAcceptedEpoch(1);
peer.setCurrentEpoch(1);
-
leadThread = new LeadThread(leader);
leadThread.start();
- while(leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
+ while (leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
Thread.sleep(20);
}
- LearnerHandler lh = new LearnerHandler(leaderSocket,
- new BufferedInputStream(leaderSocket.getInputStream()),
- leader);
+ LearnerHandler lh = new LearnerHandler(leaderSocket, new BufferedInputStream(leaderSocket.getInputStream()), leader);
lh.start();
leaderSocket.setSoTimeout(4000);
- InputArchive ia = BinaryInputArchive.getArchive(followerSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket
- .getOutputStream());
+ InputArchive ia = BinaryInputArchive.getArchive(followerSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket.getOutputStream());
conversation.converseWithLeader(ia, oa, leader, zxid);
} finally {
@@ -408,7 +406,7 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
+
public void testFollowerConversation(FollowerConversation conversation) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
@@ -420,14 +418,12 @@ public class Zab1_0Test extends ZKTestCase {
peer = createQuorumPeer(tmpDir);
follower = createFollower(tmpDir, peer);
peer.follower = follower;
-
- ServerSocket ss =
- new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
- QuorumServer leaderQS = new QuorumServer(1,
- (InetSocketAddress) ss.getLocalSocketAddress());
+
+ ServerSocket ss = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ QuorumServer leaderQS = new QuorumServer(1, (InetSocketAddress) ss.getLocalSocketAddress());
follower.setLeaderQuorumServer(leaderQS);
final Follower followerForThread = follower;
-
+
followerThread = new Thread() {
public void run() {
try {
@@ -441,11 +437,9 @@ public class Zab1_0Test extends ZKTestCase {
};
followerThread.start();
Socket leaderSocket = ss.accept();
-
- InputArchive ia = BinaryInputArchive.getArchive(leaderSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket
- .getOutputStream());
+
+ InputArchive ia = BinaryInputArchive.getArchive(leaderSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket.getOutputStream());
conversation.converseWithFollower(ia, oa, follower);
} finally {
@@ -476,8 +470,7 @@ public class Zab1_0Test extends ZKTestCase {
observer = createObserver(tmpDir, peer);
peer.observer = observer;
- ServerSocket ss =
- new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ ServerSocket ss = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
QuorumServer leaderQS = new QuorumServer(1, (InetSocketAddress) ss.getLocalSocketAddress());
observer.setLeaderQuorumServer(leaderQS);
final Observer observerForThread = observer;
@@ -486,7 +479,7 @@ public class Zab1_0Test extends ZKTestCase {
public void run() {
try {
observerForThread.observeLeader();
- } catch(Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
@@ -494,10 +487,8 @@ public class Zab1_0Test extends ZKTestCase {
observerThread.start();
Socket leaderSocket = ss.accept();
- InputArchive ia = BinaryInputArchive.getArchive(leaderSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket
- .getOutputStream());
+ InputArchive ia = BinaryInputArchive.getArchive(leaderSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket.getOutputStream());
conversation.converseWithObserver(ia, oa, observer);
} finally {
@@ -519,71 +510,67 @@ public class Zab1_0Test extends ZKTestCase {
public void testUnnecessarySnap() throws Exception {
testPopulatedLeaderConversation(new PopulatedLeaderConversation() {
@Override
- public void converseWithLeader(InputArchive ia, OutputArchive oa,
- Leader l, long zxid) throws Exception {
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l, long zxid) throws Exception {
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
/* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 1,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 1, liBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(2, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Assert.assertEquals(2, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
-
- byte epochBytes[] = new byte[4];
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(2, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ assertEquals(2, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
+
+ byte[] epochBytes = new byte[4];
final ByteBuffer wrappedEpochBytes = ByteBuffer.wrap(epochBytes);
wrappedEpochBytes.putInt(1);
qp = new QuorumPacket(Leader.ACKEPOCH, zxid, epochBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
}
}, 2);
}
-
+
// We want to track the change with a callback rather than depending on timing
class TrackerWatcher implements Watcher {
+
boolean changed;
synchronized void waitForChange() throws InterruptedException {
- while(!changed) {
+ while (!changed) {
wait();
}
}
@Override
public void process(WatchedEvent event) {
if (event.getType() == EventType.NodeDataChanged) {
- synchronized(this) {
+ synchronized (this) {
changed = true;
notifyAll();
}
}
}
- synchronized public boolean changed() {
+ public synchronized boolean changed() {
return changed;
}
- };
-
+ }
+
@Test
public void testNormalFollowerRun() throws Exception {
testFollowerConversation(new FollowerConversation() {
@Override
- public void converseWithFollower(InputArchive ia, OutputArchive oa,
- Follower f) throws Exception {
+ public void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -592,40 +579,40 @@ public class Zab1_0Test extends ZKTestCase {
//Spy on ZK so we can check if a snapshot happened or not.
f.zk = spy(f.zk);
try {
- Assert.assertEquals(0, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
+ assertEquals(0, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
// Setup a database with a single /foo node
ZKDatabase zkDb = new ZKDatabase(new FileTxnSnapLog(tmpDir, tmpDir));
final long firstZxid = ZxidUtils.makeZxid(1, 1);
zkDb.processTxn(new TxnHeader(13, 1313, firstZxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
QuorumPacket qp = new QuorumPacket();
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.FOLLOWERINFO, qp.getType());
- Assert.assertEquals(qp.getZxid(), 0);
+ assertEquals(Leader.FOLLOWERINFO, qp.getType());
+ assertEquals(qp.getZxid(), 0);
LearnerInfo learnInfo = new LearnerInfo();
ByteBufferInputStream.byteBuffer2Record(ByteBuffer.wrap(qp.getData()), learnInfo);
- Assert.assertEquals(learnInfo.getProtocolVersion(), 0x10000);
- Assert.assertEquals(learnInfo.getServerid(), 0);
-
+ assertEquals(learnInfo.getProtocolVersion(), 0x10000);
+ assertEquals(learnInfo.getServerid(), 0);
+
// We are simulating an established leader, so the epoch is 1
qp.setType(Leader.LEADERINFO);
qp.setZxid(ZxidUtils.makeZxid(1, 0));
- byte protoBytes[] = new byte[4];
+ byte[] protoBytes = new byte[4];
ByteBuffer.wrap(protoBytes).putInt(0x10000);
qp.setData(protoBytes);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACKEPOCH, qp.getType());
- Assert.assertEquals(0, qp.getZxid());
- Assert.assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
-
+ assertEquals(Leader.ACKEPOCH, qp.getType());
+ assertEquals(0, qp.getZxid());
+ assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
+
// Send the snapshot we created earlier
qp.setType(Leader.SNAP);
qp.setData(new byte[0]);
@@ -643,60 +630,60 @@ public class Zab1_0Test extends ZKTestCase {
// Get the ack of the new leader
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(1, f.self.getCurrentEpoch());
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(1, f.self.getCurrentEpoch());
//Make sure that we did take the snapshot now
verify(f.zk).takeSnapshot(true);
- Assert.assertEquals(firstZxid, f.fzk.getLastProcessedZxid());
-
+ assertEquals(firstZxid, f.fzk.getLastProcessedZxid());
+
// Make sure the data was recorded in the filesystem ok
ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
long lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data1", new String(zkDb2.getData("/foo", stat, null)));
- Assert.assertEquals(firstZxid, lastZxid);
+ assertEquals("data1", new String(zkDb2.getData("/foo", stat, null)));
+ assertEquals(firstZxid, lastZxid);
// Propose an update
long proposalZxid = ZxidUtils.makeZxid(1, 1000);
proposeSetData(qp, proposalZxid, "data2", 2);
oa.writeRecord(qp, null);
-
+
TrackerWatcher watcher = new TrackerWatcher();
-
+
// The change should not have happened yet, since we haven't committed
- Assert.assertEquals("data1", new String(f.fzk.getZKDatabase().getData("/foo", stat, watcher)));
-
+ assertEquals("data1", new String(f.fzk.getZKDatabase().getData("/foo", stat, watcher)));
+
// The change should happen now
qp.setType(Leader.COMMIT);
qp.setZxid(proposalZxid);
oa.writeRecord(qp, null);
-
+
qp.setType(Leader.UPTODATE);
qp.setZxid(0);
oa.writeRecord(qp, null);
-
+
// Read the uptodate ack
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(proposalZxid, qp.getZxid());
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(proposalZxid, qp.getZxid());
+
watcher.waitForChange();
- Assert.assertEquals("data2", new String(f.fzk.getZKDatabase().getData("/foo", stat, null)));
-
+ assertEquals("data2", new String(f.fzk.getZKDatabase().getData("/foo", stat, null)));
+
// check and make sure the change is persisted
zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data2", new String(zkDb2.getData("/foo", stat, null)));
- Assert.assertEquals(proposalZxid, lastZxid);
+ assertEquals("data2", new String(zkDb2.getData("/foo", stat, null)));
+ assertEquals(proposalZxid, lastZxid);
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
-
+
}
private void proposeSetData(QuorumPacket qp, long zxid, String data, int version) throws IOException {
@@ -712,13 +699,12 @@ public class Zab1_0Test extends ZKTestCase {
}
});
}
-
+
@Test
public void testNormalFollowerRunWithDiff() throws Exception {
testFollowerConversation(new FollowerConversation() {
@Override
- public void converseWithFollower(InputArchive ia, OutputArchive oa,
- Follower f) throws Exception {
+ public void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -727,40 +713,40 @@ public class Zab1_0Test extends ZKTestCase {
//Spy on ZK so we can check if a snapshot happened or not.
f.zk = spy(f.zk);
try {
- Assert.assertEquals(0, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
+ assertEquals(0, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
// Setup a database with a single /foo node
ZKDatabase zkDb = new ZKDatabase(new FileTxnSnapLog(tmpDir, tmpDir));
final long firstZxid = ZxidUtils.makeZxid(1, 1);
zkDb.processTxn(new TxnHeader(13, 1313, firstZxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
QuorumPacket qp = new QuorumPacket();
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.FOLLOWERINFO, qp.getType());
- Assert.assertEquals(qp.getZxid(), 0);
+ assertEquals(Leader.FOLLOWERINFO, qp.getType());
+ assertEquals(qp.getZxid(), 0);
LearnerInfo learnInfo = new LearnerInfo();
ByteBufferInputStream.byteBuffer2Record(ByteBuffer.wrap(qp.getData()), learnInfo);
- Assert.assertEquals(learnInfo.getProtocolVersion(), 0x10000);
- Assert.assertEquals(learnInfo.getServerid(), 0);
-
+ assertEquals(learnInfo.getProtocolVersion(), 0x10000);
+ assertEquals(learnInfo.getServerid(), 0);
+
// We are simulating an established leader, so the epoch is 1
qp.setType(Leader.LEADERINFO);
qp.setZxid(ZxidUtils.makeZxid(1, 0));
- byte protoBytes[] = new byte[4];
+ byte[] protoBytes = new byte[4];
ByteBuffer.wrap(protoBytes).putInt(0x10000);
qp.setData(protoBytes);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACKEPOCH, qp.getType());
- Assert.assertEquals(0, qp.getZxid());
- Assert.assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
-
+ assertEquals(Leader.ACKEPOCH, qp.getType());
+ assertEquals(0, qp.getZxid());
+ assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
+
// Send a diff
qp.setType(Leader.DIFF);
qp.setData(new byte[0]);
@@ -779,29 +765,29 @@ public class Zab1_0Test extends ZKTestCase {
qp.setType(Leader.UPTODATE);
qp.setZxid(0);
oa.writeRecord(qp, null);
-
+
// Read the uptodate ack
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
-
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+
// Get the ack of the new leader
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(1, f.self.getCurrentEpoch());
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(1, f.self.getCurrentEpoch());
+
//Wait for the transactions to be written out. The thread that writes them out
// does not send anything back when it is done.
long start = System.currentTimeMillis();
- while (createSessionZxid != f.fzk.getLastProcessedZxid() && (System.currentTimeMillis() - start) < 50) {
+ while (createSessionZxid != f.fzk.getLastProcessedZxid()
+ && (System.currentTimeMillis() - start) < 50) {
Thread.sleep(1);
}
-
- Assert.assertEquals(createSessionZxid, f.fzk.getLastProcessedZxid());
-
+
+ assertEquals(createSessionZxid, f.fzk.getLastProcessedZxid());
+
// Make sure the data was recorded in the filesystem ok
ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
start = System.currentTimeMillis();
@@ -812,13 +798,13 @@ public class Zab1_0Test extends ZKTestCase {
}
LOG.info("zkdb2 sessions:" + zkDb2.getSessions());
LOG.info("zkdb2 with timeouts:" + zkDb2.getSessionWithTimeOuts());
- Assert.assertNotNull(zkDb2.getSessionWithTimeOuts().get(4L));
+ assertNotNull(zkDb2.getSessionWithTimeOuts().get(4L));
//Snapshot was never taken during very simple sync
verify(f.zk, never()).takeSnapshot();
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
-
+
}
private void proposeNewSession(QuorumPacket qp, long zxid, long sessionId) throws IOException {
@@ -834,49 +820,45 @@ public class Zab1_0Test extends ZKTestCase {
}
});
}
-
+
@Test
public void testNormalRun() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException {
- Assert.assertEquals(0, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException {
+ assertEquals(0, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
/* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0, liBytes, null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACKEPOCH, 0, new byte[4], null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.NEWLEADER, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.NEWLEADER, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACK, qp.getZxid(), null, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.UPTODATE, qp.getType());
+ assertEquals(Leader.UPTODATE, qp.getType());
}
});
}
@@ -884,52 +866,46 @@ public class Zab1_0Test extends ZKTestCase {
@Test
public void testTxnTimeout() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException, InterruptedException, org.apache.zookeeper.server.quorum.Leader.XidRolloverException {
- Assert.assertEquals(0, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException, InterruptedException, org.apache.zookeeper.server.quorum.Leader.XidRolloverException {
+ assertEquals(0, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0, liBytes, null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACKEPOCH, 0, new byte[4], null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.NEWLEADER, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.NEWLEADER, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACK, qp.getZxid(), null, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.UPTODATE, qp.getType());
+ assertEquals(Leader.UPTODATE, qp.getType());
long zxid = l.zk.getZxid();
- l.propose(new Request(1, 1, ZooDefs.OpCode.create,
- new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.create),
- new CreateTxn("/test", "hola".getBytes(), null, true, 0), zxid));
+ l.propose(new Request(1, 1, ZooDefs.OpCode.create, new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.create), new CreateTxn("/test", "hola".getBytes(), null, true, 0), zxid));
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.PROPOSAL, qp.getType());
+ assertEquals(Leader.PROPOSAL, qp.getType());
LOG.info("Proposal sent.");
@@ -937,19 +913,18 @@ public class Zab1_0Test extends ZKTestCase {
try {
ia.readRecord(qp, null);
LOG.info("Ping received: " + i);
- qp = new QuorumPacket(Leader.PING, qp.getZxid(), "".getBytes(), null);
+ qp = new QuorumPacket(Leader.PING, qp.getZxid(), "".getBytes(), null);
oa.writeRecord(qp, null);
} catch (EOFException e) {
return;
}
}
- Assert.fail("Connection hasn't been closed by leader after transaction times out.");
+ fail("Connection hasn't been closed by leader after transaction times out.");
}
});
}
- private void deserializeSnapshot(InputArchive ia)
- throws IOException {
+ private void deserializeSnapshot(InputArchive ia) throws IOException {
ZKDatabase zkdb = new ZKDatabase(null);
zkdb.deserializeSnapshot(ia);
String signature = ia.readString("signature");
@@ -960,60 +935,49 @@ public class Zab1_0Test extends ZKTestCase {
public void testNormalObserverRun() throws Exception {
testObserverConversation(new ObserverConversation() {
@Override
- public void converseWithObserver(InputArchive ia, OutputArchive oa,
- Observer o) throws Exception {
+ public void converseWithObserver(InputArchive ia, OutputArchive oa, Observer o) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
File logDir = o.zk.getTxnLogFactory().getDataDir().getParentFile();
File snapDir = o.zk.getTxnLogFactory().getSnapDir().getParentFile();
try {
- Assert.assertEquals(0, o.self.getAcceptedEpoch());
- Assert.assertEquals(0, o.self.getCurrentEpoch());
+ assertEquals(0, o.self.getAcceptedEpoch());
+ assertEquals(0, o.self.getCurrentEpoch());
// Setup a database with a single /foo node
ZKDatabase zkDb = new ZKDatabase(new FileTxnSnapLog(tmpDir, tmpDir));
final long foo1Zxid = ZxidUtils.makeZxid(1, 1);
final long foo2Zxid = ZxidUtils.makeZxid(1, 2);
- zkDb.processTxn(new TxnHeader(13, 1313, foo1Zxid, 33,
- ZooDefs.OpCode.create), new CreateTxn("/foo1",
- "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- false, 1));
- zkDb.processTxn(new TxnHeader(13, 1313, foo2Zxid, 33,
- ZooDefs.OpCode.create), new CreateTxn("/foo2",
- "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- false, 1));
+ zkDb.processTxn(new TxnHeader(13, 1313, foo1Zxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo1", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
+ zkDb.processTxn(new TxnHeader(13, 1313, foo2Zxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo2", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("data1",
- new String(zkDb.getData("/foo1", stat, null)));
- Assert.assertEquals("data1",
- new String(zkDb.getData("/foo2", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo1", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo2", stat, null)));
QuorumPacket qp = new QuorumPacket();
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.OBSERVERINFO, qp.getType());
- Assert.assertEquals(qp.getZxid(), 0);
+ assertEquals(Leader.OBSERVERINFO, qp.getType());
+ assertEquals(qp.getZxid(), 0);
LearnerInfo learnInfo = new LearnerInfo();
- ByteBufferInputStream.byteBuffer2Record(
- ByteBuffer.wrap(qp.getData()), learnInfo);
- Assert.assertEquals(learnInfo.getProtocolVersion(), 0x10000);
- Assert.assertEquals(learnInfo.getServerid(), 0);
+ ByteBufferInputStream.byteBuffer2Record(ByteBuffer.wrap(qp.getData()), learnInfo);
+ assertEquals(learnInfo.getProtocolVersion(), 0x10000);
+ assertEquals(learnInfo.getServerid(), 0);
// We are simulating an established leader, so the epoch is 1
qp.setType(Leader.LEADERINFO);
qp.setZxid(ZxidUtils.makeZxid(1, 0));
- byte protoBytes[] = new byte[4];
+ byte[] protoBytes = new byte[4];
ByteBuffer.wrap(protoBytes).putInt(0x10000);
qp.setData(protoBytes);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACKEPOCH, qp.getType());
- Assert.assertEquals(0, qp.getZxid());
- Assert.assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer
- .wrap(qp.getData()).getInt());
- Assert.assertEquals(1, o.self.getAcceptedEpoch());
- Assert.assertEquals(0, o.self.getCurrentEpoch());
+ assertEquals(Leader.ACKEPOCH, qp.getType());
+ assertEquals(0, qp.getZxid());
+ assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
+ assertEquals(1, o.self.getAcceptedEpoch());
+ assertEquals(0, o.self.getCurrentEpoch());
// Send the snapshot we created earlier
qp.setType(Leader.SNAP);
@@ -1028,25 +992,22 @@ public class Zab1_0Test extends ZKTestCase {
// Get the ack of the new leader
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, o.self.getAcceptedEpoch());
- Assert.assertEquals(1, o.self.getCurrentEpoch());
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, o.self.getAcceptedEpoch());
+ assertEquals(1, o.self.getCurrentEpoch());
- Assert.assertEquals(foo2Zxid, o.zk.getLastProcessedZxid());
+ assertEquals(foo2Zxid, o.zk.getLastProcessedZxid());
// Make sure the data was recorded in the filesystem ok
- ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(
- logDir, snapDir));
+ ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
long lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data1",
- new String(zkDb2.getData("/foo1", stat, null)));
- Assert.assertEquals(foo2Zxid, lastZxid);
+ assertEquals("data1", new String(zkDb2.getData("/foo1", stat, null)));
+ assertEquals(foo2Zxid, lastZxid);
// Register watch
TrackerWatcher watcher = new TrackerWatcher();
- Assert.assertEquals("data1", new String(o.zk
- .getZKDatabase().getData("/foo2", stat, watcher)));
+ assertEquals("data1", new String(o.zk.getZKDatabase().getData("/foo2", stat, watcher)));
// Propose /foo1 update
long proposalZxid = ZxidUtils.makeZxid(1, 1000);
@@ -1070,15 +1031,13 @@ public class Zab1_0Test extends ZKTestCase {
// Read the uptodate ack
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
// Data should get updated
watcher.waitForChange();
- Assert.assertEquals("data2", new String(o.zk
- .getZKDatabase().getData("/foo1", stat, null)));
- Assert.assertEquals("data2", new String(o.zk
- .getZKDatabase().getData("/foo2", stat, null)));
+ assertEquals("data2", new String(o.zk.getZKDatabase().getData("/foo1", stat, null)));
+ assertEquals("data2", new String(o.zk.getZKDatabase().getData("/foo2", stat, null)));
// Shutdown sequence guarantee that all pending requests
// in sync request processor get flush to disk
@@ -1086,21 +1045,19 @@ public class Zab1_0Test extends ZKTestCase {
zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data2", new String(zkDb2.getData("/foo1", stat, null)));
- Assert.assertEquals("data2", new String(zkDb2.getData("/foo2", stat, null)));
- Assert.assertEquals(informZxid, lastZxid);
+ assertEquals("data2", new String(zkDb2.getData("/foo1", stat, null)));
+ assertEquals("data2", new String(zkDb2.getData("/foo2", stat, null)));
+ assertEquals(informZxid, lastZxid);
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
}
- private void proposeSetData(QuorumPacket qp, String path,
- long zxid, String data, int version) throws IOException {
+ private void proposeSetData(QuorumPacket qp, String path, long zxid, String data, int version) throws IOException {
qp.setType(Leader.PROPOSAL);
qp.setZxid(zxid);
- TxnHeader hdr = new TxnHeader(4, 1414, qp.getZxid(), 55,
- ZooDefs.OpCode.setData);
+ TxnHeader hdr = new TxnHeader(4, 1414, qp.getZxid(), 55, ZooDefs.OpCode.setData);
SetDataTxn sdt = new SetDataTxn(path, data.getBytes(), version);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputArchive boa = BinaryOutputArchive.getArchive(baos);
@@ -1114,35 +1071,31 @@ public class Zab1_0Test extends ZKTestCase {
@Test
public void testLeaderBehind() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException {
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException {
/* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
/* we are going to say we last acked epoch 20 */
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, ZxidUtils.makeZxid(20, 0),
- liBytes, null);
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, ZxidUtils.makeZxid(20, 0), liBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
qp = new QuorumPacket(Leader.ACKEPOCH, 0, new byte[4], null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.NEWLEADER, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
+ assertEquals(Leader.NEWLEADER, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
qp = new QuorumPacket(Leader.ACK, qp.getZxid(), null, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.UPTODATE, qp.getType());
+ assertEquals(Leader.UPTODATE, qp.getType());
}
});
}
@@ -1156,29 +1109,25 @@ public class Zab1_0Test extends ZKTestCase {
@Test
public void testAbandonBeforeACKEpoch() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException, InterruptedException {
- /* we test a normal run. everything should work out well. */
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException, InterruptedException {
+ /* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0, liBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Thread.sleep(l.self.getInitLimit()*l.self.getTickTime() + 5000);
-
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ Thread.sleep(l.self.getInitLimit() * l.self.getTickTime() + 5000);
+
// The leader didn't get a quorum of acks - make sure that leader's current epoch is not advanced
- Assert.assertEquals(0, l.self.getCurrentEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
}
});
}
-
+
static class ConversableFollower extends Follower {
ConversableFollower(QuorumPeer self, FollowerZooKeeperServer zk) {
@@ -1189,14 +1138,14 @@ public class Zab1_0Test extends ZKTestCase {
public void setLeaderQuorumServer(QuorumServer quorumServer) {
leaderQuorumServer = quorumServer;
}
-
+
@Override
protected QuorumServer findLeader() {
return leaderQuorumServer;
}
+
}
- private ConversableFollower createFollower(File tmpDir, QuorumPeer peer)
- throws IOException {
+ private ConversableFollower createFollower(File tmpDir, QuorumPeer peer) throws IOException {
FileTxnSnapLog logFactory = new FileTxnSnapLog(tmpDir, tmpDir);
peer.setTxnFactory(logFactory);
ZKDatabase zkDb = new ZKDatabase(logFactory);
@@ -1220,10 +1169,10 @@ public class Zab1_0Test extends ZKTestCase {
protected QuorumServer findLeader() {
return leaderQuorumServer;
}
+
}
- private ConversableObserver createObserver(File tmpDir, QuorumPeer peer)
- throws IOException {
+ private ConversableObserver createObserver(File tmpDir, QuorumPeer peer) throws IOException {
FileTxnSnapLog logFactory = new FileTxnSnapLog(tmpDir, tmpDir);
peer.setTxnFactory(logFactory);
ZKDatabase zkDb = new ZKDatabase(logFactory);
@@ -1247,25 +1196,20 @@ public class Zab1_0Test extends ZKTestCase {
version2.mkdir();
logFactory.save(new DataTree(), new ConcurrentHashMap<Long, Integer>(), false);
long zxid = ZxidUtils.makeZxid(3, 3);
- logFactory.append(new Request(1, 1, ZooDefs.OpCode.error,
- new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.error),
- new ErrorTxn(1), zxid));
+ logFactory.append(new Request(1, 1, ZooDefs.OpCode.error, new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.error), new ErrorTxn(1), zxid));
logFactory.commit();
ZKDatabase zkDb = new ZKDatabase(logFactory);
QuorumPeer peer = QuorumPeer.testingQuorumPeer();
peer.setZKDatabase(zkDb);
peer.setTxnFactory(logFactory);
peer.getLastLoggedZxid();
- Assert.assertEquals(3, peer.getAcceptedEpoch());
- Assert.assertEquals(3, peer.getCurrentEpoch());
- Assert.assertEquals(3, Integer
- .parseInt(readContentsOfFile(new File(version2,
- QuorumPeer.CURRENT_EPOCH_FILENAME))));
- Assert.assertEquals(3, Integer
- .parseInt(readContentsOfFile(new File(version2,
- QuorumPeer.ACCEPTED_EPOCH_FILENAME))));
+ assertEquals(3, peer.getAcceptedEpoch());
+ assertEquals(3, peer.getCurrentEpoch());
+ assertEquals(3, Integer.parseInt(readContentsOfFile(new File(version2, QuorumPeer.CURRENT_EPOCH_FILENAME))));
+ assertEquals(3, Integer.parseInt(readContentsOfFile(new File(version2, QuorumPeer.ACCEPTED_EPOCH_FILENAME))));
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java
index 09bcde80e..fff5e62de 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,6 +18,12 @@
package org.apache.zookeeper.server.quorum;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.server.ServerCnxn;
@@ -28,39 +34,23 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.flexible.QuorumMaj;
import org.apache.zookeeper.test.ClientBase;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-
public class ZabUtils {
- private ZabUtils() {}
+ private ZabUtils() {
+ }
public static final int SYNC_LIMIT = 2;
- public static QuorumPeer createQuorumPeer(File tmpDir) throws IOException, FileNotFoundException {
+ public static QuorumPeer createQuorumPeer(File tmpDir) throws IOException {
HashMap<Long, QuorumPeer.QuorumServer> peers = new HashMap<Long, QuorumPeer.QuorumServer>();
QuorumPeer peer = QuorumPeer.testingQuorumPeer();
peer.syncLimit = SYNC_LIMIT;
peer.initLimit = 2;
peer.tickTime = 2000;
- peers.put(0L, new QuorumPeer.QuorumServer(
- 0, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
- peers.put(1L, new QuorumPeer.QuorumServer(
- 1, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
- peers.put(2L, new QuorumPeer.QuorumServer(
- 2, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ peers.put(0L, new QuorumPeer.QuorumServer(0, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ peers.put(1L, new QuorumPeer.QuorumServer(1, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ peers.put(2L, new QuorumPeer.QuorumServer(2, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
peer.setQuorumVerifier(new QuorumMaj(peers), false);
peer.setCnxnFactory(new NullServerCnxnFactory());
@@ -76,20 +66,17 @@ public class ZabUtils {
return peer;
}
- public static Leader createLeader(File tmpDir, QuorumPeer peer)
- throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
+ public static Leader createLeader(File tmpDir, QuorumPeer peer) throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
LeaderZooKeeperServer zk = prepareLeader(tmpDir, peer);
return new Leader(peer, zk);
}
- public static Leader createMockLeader(File tmpDir, QuorumPeer peer)
- throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
+ public static Leader createMockLeader(File tmpDir, QuorumPeer peer) throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
LeaderZooKeeperServer zk = prepareLeader(tmpDir, peer);
return new MockLeader(peer, zk);
}
- private static LeaderZooKeeperServer prepareLeader(File tmpDir, QuorumPeer peer)
- throws IOException, NoSuchFieldException, IllegalAccessException {
+ private static LeaderZooKeeperServer prepareLeader(File tmpDir, QuorumPeer peer) throws IOException, NoSuchFieldException, IllegalAccessException {
FileTxnSnapLog logFactory = new FileTxnSnapLog(tmpDir, tmpDir);
peer.setTxnFactory(logFactory);
ZKDatabase zkDb = new ZKDatabase(logFactory);
@@ -98,8 +85,8 @@ public class ZabUtils {
}
private static final class NullServerCnxnFactory extends ServerCnxnFactory {
- public void startup(ZooKeeperServer zkServer, boolean startServer)
- throws IOException, InterruptedException {
+
+ public void startup(ZooKeeperServer zkServer, boolean startServer) throws IOException, InterruptedException {
}
public void start() {
}
@@ -124,8 +111,7 @@ public class ZabUtils {
public Iterable<ServerCnxn> getConnections() {
return null;
}
- public void configure(InetSocketAddress addr, int maxcc, int listenBacklog,
- boolean secure) throws IOException {
+ public void configure(InetSocketAddress addr, int maxcc, int listenBacklog, boolean secure) throws IOException {
}
@Override
@@ -149,12 +135,12 @@ public class ZabUtils {
public Iterable<Map<String, Object>> getAllConnectionInfo(boolean brief) {
return null;
}
+
}
public static final class MockLeader extends Leader {
- MockLeader(QuorumPeer qp, LeaderZooKeeperServer zk)
- throws IOException, X509Exception {
+ MockLeader(QuorumPeer qp, LeaderZooKeeperServer zk) throws IOException, X509Exception {
super(qp, zk);
}
@@ -168,5 +154,7 @@ public class ZabUtils {
public long getCurrentEpochToPropose() {
return epoch;
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
index 9617c70b3..cc6af7be5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -15,18 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.server.quorum.auth;
-import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
+package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
+import org.apache.commons.io.FileUtils;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
/*
* This code is originally from HDFS, see the similarly named file there
@@ -47,6 +46,7 @@ import java.util.Properties;
* createMiniKdcConf() to provide new settings.
*/
public class KerberosSecurityTestcase extends QuorumAuthTestBase {
+
private static MiniKdc kdc;
private static File workDir;
private static Properties conf;
@@ -78,8 +78,7 @@ public class KerberosSecurityTestcase extends QuorumAuthTestBase {
* @throws IOException
*/
public static void createTestDir() throws IOException {
- workDir = createTmpDir(
- new File(System.getProperty("build.test.dir", "build")));
+ workDir = createTmpDir(new File(System.getProperty("build.test.dir", "build")));
}
static File createTmpDir(File parentDir) throws IOException {
@@ -88,8 +87,8 @@ public class KerberosSecurityTestcase extends QuorumAuthTestBase {
// a tmpDir with a duplicate name
File tmpDir = new File(tmpFile + ".dir");
// never true if tmpfile does it's job
- Assert.assertFalse(tmpDir.exists());
- Assert.assertTrue(tmpDir.mkdirs());
+ assertFalse(tmpDir.exists());
+ assertTrue(tmpDir.mkdirs());
return tmpDir;
}
@@ -117,4 +116,5 @@ public class KerberosSecurityTestcase extends QuorumAuthTestBase {
public static Properties getConf() {
return conf;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java
index 41609fa77..30dd3e4db 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -20,12 +20,11 @@ package org.apache.zookeeper.server.quorum.auth;
import java.io.File;
import java.util.UUID;
-
import org.apache.zookeeper.util.SecurityUtils;
public class KerberosTestUtils {
- private static String keytabFile = new File(System.getProperty("build.test.dir", "build"), UUID.randomUUID().toString())
- .getAbsolutePath();
+
+ private static String keytabFile = new File(System.getProperty("build.test.dir", "build"), UUID.randomUUID().toString()).getAbsolutePath();
public static String getRealm() {
return "EXAMPLE.COM";
@@ -57,8 +56,9 @@ public class KerberosTestUtils {
public static String replaceHostPattern(String principal) {
String[] components = principal.split("[/@]");
- if (components == null || components.length < 2
- || !components[1].equals(SecurityUtils.QUORUM_HOSTNAME_PATTERN)) {
+ if (components == null
+ || components.length < 2
+ || !components[1].equals(SecurityUtils.QUORUM_HOSTNAME_PATTERN)) {
return principal;
} else {
return replacePattern(components, "localhost");
@@ -67,10 +67,10 @@ public class KerberosTestUtils {
public static String replacePattern(String[] components, String hostname) {
if (components.length == 3) {
- return components[0] + "/" + hostname.toLowerCase() + "@"
- + components[2];
+ return components[0] + "/" + hostname.toLowerCase() + "@" + components[2];
} else {
return components[0] + "/" + hostname.toLowerCase();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java
index 244735ee1..56902d778 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -17,20 +17,12 @@
*/
package org.apache.zookeeper.server.quorum.auth;
-import org.apache.kerby.kerberos.kerb.KrbException;
-import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
-import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
-import org.apache.kerby.util.IOUtil;
-import org.apache.kerby.util.NetworkUtil;
-import org.apache.zookeeper.server.ExitCode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
@@ -38,6 +30,14 @@ import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
+import org.apache.kerby.kerberos.kerb.KrbException;
+import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
+import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
+import org.apache.kerby.util.IOUtil;
+import org.apache.kerby.util.NetworkUtil;
+import org.apache.zookeeper.server.ExitCode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Mini KDC based on Apache Directory Server that can be embedded in testcases
@@ -78,27 +78,22 @@ import java.util.Set;
*/
public class MiniKdc {
- public static final String JAVA_SECURITY_KRB5_CONF =
- "java.security.krb5.conf";
- public static final String SUN_SECURITY_KRB5_DEBUG =
- "sun.security.krb5.debug";
+ public static final String JAVA_SECURITY_KRB5_CONF = "java.security.krb5.conf";
+ public static final String SUN_SECURITY_KRB5_DEBUG = "sun.security.krb5.debug";
public static void main(String[] args) throws Exception {
if (args.length < 4) {
- System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " +
- "<KEYTABFILE> [<PRINCIPALS>]+");
+ System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " + "<KEYTABFILE> [<PRINCIPALS>]+");
System.exit(ExitCode.UNEXPECTED_ERROR.getValue());
}
File workDir = new File(args[0]);
if (!workDir.exists()) {
- throw new RuntimeException("Specified work directory does not exists: "
- + workDir.getAbsolutePath());
+ throw new RuntimeException("Specified work directory does not exists: " + workDir.getAbsolutePath());
}
Properties conf = createConf();
File file = new File(args[1]);
if (!file.exists()) {
- throw new RuntimeException("Specified configuration does not exists: "
- + file.getAbsolutePath());
+ throw new RuntimeException("Specified configuration does not exists: " + file.getAbsolutePath());
}
Properties userConf = new Properties();
InputStreamReader r = null;
@@ -125,8 +120,7 @@ public class MiniKdc {
System.out.println("Standalone MiniKdc Running");
System.out.println("---------------------------------------------------");
System.out.println(" Realm : " + miniKdc.getRealm());
- System.out.println(" Running at : " + miniKdc.getHost() + ":" +
- miniKdc.getHost());
+ System.out.println(" Running at : " + miniKdc.getHost() + ":" + miniKdc.getHost());
System.out.println(" krb5conf : " + krb5conf);
System.out.println();
System.out.println(" created keytab : " + keytabFile);
@@ -142,8 +136,7 @@ public class MiniKdc {
}
});
} else {
- throw new RuntimeException("Cannot rename KDC's krb5conf to "
- + krb5conf.getAbsolutePath());
+ throw new RuntimeException("Cannot rename KDC's krb5conf to " + krb5conf.getAbsolutePath());
}
}
@@ -220,12 +213,10 @@ public class MiniKdc {
if (!conf.keySet().containsAll(PROPERTIES)) {
Set<String> missingProperties = new HashSet<String>(PROPERTIES);
missingProperties.removeAll(conf.keySet());
- throw new IllegalArgumentException("Missing configuration properties: "
- + missingProperties);
+ throw new IllegalArgumentException("Missing configuration properties: " + missingProperties);
}
this.workDir = new File(workDir, Long.toString(System.currentTimeMillis()));
- if (!this.workDir.exists()
- && !this.workDir.mkdirs()) {
+ if (!this.workDir.exists() && !this.workDir.mkdirs()) {
throw new RuntimeException("Cannot create directory " + this.workDir);
}
LOG.info("Configuration:");
@@ -236,10 +227,9 @@ public class MiniKdc {
LOG.info("---------------------------------------------------------------");
this.conf = conf;
port = Integer.parseInt(conf.getProperty(KDC_PORT));
- String orgName= conf.getProperty(ORG_NAME);
+ String orgName = conf.getProperty(ORG_NAME);
String orgDomain = conf.getProperty(ORG_DOMAIN);
- realm = orgName.toUpperCase(Locale.ENGLISH) + "."
- + orgDomain.toUpperCase(Locale.ENGLISH);
+ realm = orgName.toUpperCase(Locale.ENGLISH) + "." + orgDomain.toUpperCase(Locale.ENGLISH);
}
/**
@@ -292,11 +282,9 @@ public class MiniKdc {
}
private void resetDefaultRealm() throws IOException {
- InputStream templateResource = new FileInputStream(
- getKrb5conf().getAbsolutePath());
+ InputStream templateResource = new FileInputStream(getKrb5conf().getAbsolutePath());
String content = IOUtil.readInput(templateResource);
- content = content.replaceAll("default_realm = .*\n",
- "default_realm = " + getRealm() + "\n");
+ content = content.replaceAll("default_realm = .*\n", "default_realm = " + getRealm() + "\n");
IOUtil.writeFile(content, getKrb5conf());
}
@@ -324,8 +312,7 @@ public class MiniKdc {
} else {
throw new IllegalArgumentException("Need to set transport!");
}
- simpleKdc.getKdcConfig().setString(KdcConfigKey.KDC_SERVICE_NAME,
- conf.getProperty(INSTANCE));
+ simpleKdc.getKdcConfig().setString(KdcConfigKey.KDC_SERVICE_NAME, conf.getProperty(INSTANCE));
if (conf.getProperty(DEBUG) != null) {
krb5Debug = getAndSet(SUN_SECURITY_KRB5_DEBUG, conf.getProperty(DEBUG));
}
@@ -341,9 +328,8 @@ public class MiniKdc {
} catch (KrbException e) {
e.printStackTrace();
} finally {
- if(conf.getProperty(DEBUG) != null) {
- System.setProperty(SUN_SECURITY_KRB5_DEBUG,
- Boolean.toString(krb5Debug));
+ if (conf.getProperty(DEBUG) != null) {
+ System.setProperty(SUN_SECURITY_KRB5_DEBUG, Boolean.toString(krb5Debug));
}
}
}
@@ -359,14 +345,14 @@ public class MiniKdc {
private void delete(File f) {
if (f.isFile()) {
- if (! f.delete()) {
+ if (!f.delete()) {
LOG.warn("WARNING: cannot delete file " + f.getAbsolutePath());
}
} else {
- for (File c: f.listFiles()) {
+ for (File c : f.listFiles()) {
delete(c);
}
- if (! f.delete()) {
+ if (!f.delete()) {
LOG.warn("WARNING: cannot delete directory " + f.getAbsolutePath());
}
}
@@ -379,8 +365,7 @@ public class MiniKdc {
* @param password password.
* @throws Exception thrown if the principal could not be created.
*/
- public synchronized void createPrincipal(String principal, String password)
- throws Exception {
+ public synchronized void createPrincipal(String principal, String password) throws Exception {
simpleKdc.createPrincipal(principal, password);
}
@@ -392,9 +377,7 @@ public class MiniKdc {
* @throws Exception thrown if the principals or the keytab file could not be
* created.
*/
- public synchronized void createPrincipal(File keytabFile,
- String ... principals)
- throws Exception {
+ public synchronized void createPrincipal(File keytabFile, String... principals) throws Exception {
simpleKdc.createPrincipals(principals);
if (keytabFile.exists() && !keytabFile.delete()) {
LOG.error("Failed to delete keytab file: " + keytabFile);
@@ -416,4 +399,5 @@ public class MiniKdc {
System.setProperty(sysprop, debug);
return old;
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java
index 69dbcd1e5..659551558 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,24 +18,24 @@
package org.apache.zookeeper.server.quorum.auth;
-import org.apache.kerby.kerberos.kerb.keytab.Keytab;
-import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import java.io.File;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
-import java.io.File;
-import java.security.Principal;
-import java.util.List;
-import java.util.Set;
-import java.util.Map;
-import java.util.HashSet;
-import java.util.HashMap;
-import java.util.Arrays;
+import org.apache.kerby.kerberos.kerb.keytab.Keytab;
+import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
+import org.junit.Test;
/*
* This code is originally from HDFS, see the file name TestMiniKdc there
@@ -45,13 +45,13 @@ import java.util.Arrays;
* Github Revision: 916140604ffef59466ba30832478311d3e6249bd
*/
public class MiniKdcTest extends KerberosSecurityTestcase {
- private static final boolean IBM_JAVA = System.getProperty("java.vendor")
- .contains("IBM");
+
+ private static final boolean IBM_JAVA = System.getProperty("java.vendor").contains("IBM");
@Test(timeout = 60000)
public void testMiniKdcStart() {
MiniKdc kdc = getKdc();
- Assert.assertNotSame(0, kdc.getPort());
+ assertNotSame(0, kdc.getPort());
}
@Test(timeout = 60000)
@@ -60,45 +60,42 @@ public class MiniKdcTest extends KerberosSecurityTestcase {
File workDir = getWorkDir();
kdc.createPrincipal(new File(workDir, "keytab"), "foo/bar", "bar/foo");
- List<PrincipalName> principalNameList =
- Keytab.loadKeytab(new File(workDir, "keytab")).getPrincipals();
+ List<PrincipalName> principalNameList = Keytab.loadKeytab(new File(workDir, "keytab")).getPrincipals();
Set<String> principals = new HashSet<String>();
for (PrincipalName principalName : principalNameList) {
- principals.add(principalName.getName());
+ principals.add(principalName.getName());
}
- Assert.assertEquals(new HashSet<String>(Arrays.asList(
- "foo/bar@" + kdc.getRealm(), "bar/foo@" + kdc.getRealm())),
- principals);
- }
+ assertEquals(
+ new HashSet<>(Arrays.asList("foo/bar@" + kdc.getRealm(), "bar/foo@" + kdc.getRealm())),
+ principals);
+ }
private static class KerberosConfiguration extends Configuration {
+
private String principal;
private String keytab;
private boolean isInitiator;
- private KerberosConfiguration(String principal, File keytab,
- boolean client) {
+ private KerberosConfiguration(String principal, File keytab, boolean client) {
this.principal = principal;
this.keytab = keytab.getAbsolutePath();
this.isInitiator = client;
}
- public static Configuration createClientConfig(String principal,
- File keytab) {
+ public static Configuration createClientConfig(String principal, File keytab) {
return new KerberosConfiguration(principal, keytab, true);
}
- public static Configuration createServerConfig(String principal,
- File keytab) {
+ public static Configuration createServerConfig(String principal, File keytab) {
return new KerberosConfiguration(principal, keytab, false);
}
private static String getKrb5LoginModuleName() {
return System.getProperty("java.vendor").contains("IBM")
- ? "com.ibm.security.auth.module.Krb5LoginModule"
- : "com.sun.security.auth.module.Krb5LoginModule";
+ ? "com.ibm.security.auth.module.Krb5LoginModule"
+ : "com.sun.security.auth.module.Krb5LoginModule";
}
@Override
@@ -124,11 +121,9 @@ public class MiniKdcTest extends KerberosSecurityTestcase {
}
options.put("debug", "true");
- return new AppConfigurationEntry[] {
- new AppConfigurationEntry(getKrb5LoginModuleName(),
- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
- options) };
+ return new AppConfigurationEntry[]{new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)};
}
+
}
@Test(timeout = 60000)
@@ -145,38 +140,29 @@ public class MiniKdcTest extends KerberosSecurityTestcase {
principals.add(new KerberosPrincipal(principal));
// client login
- Subject subject = new Subject(false, principals,
- new HashSet<Object>(), new HashSet<Object>());
- loginContext = new LoginContext("", subject, null,
- KerberosConfiguration.createClientConfig(principal,
- keytab));
+ Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
+ loginContext = new LoginContext("", subject, null, KerberosConfiguration.createClientConfig(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
- Assert.assertEquals(1, subject.getPrincipals().size());
- Assert.assertEquals(KerberosPrincipal.class,
- subject.getPrincipals().iterator().next().getClass());
- Assert.assertEquals(principal + "@" + kdc.getRealm(),
- subject.getPrincipals().iterator().next().getName());
+ assertEquals(1, subject.getPrincipals().size());
+ assertEquals(KerberosPrincipal.class, subject.getPrincipals().iterator().next().getClass());
+ assertEquals(principal + "@" + kdc.getRealm(), subject.getPrincipals().iterator().next().getName());
loginContext.logout();
// server login
- subject = new Subject(false, principals, new HashSet<Object>(),
- new HashSet<Object>());
- loginContext = new LoginContext("", subject, null,
- KerberosConfiguration.createServerConfig(principal,
- keytab));
+ subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
+ loginContext = new LoginContext("", subject, null, KerberosConfiguration.createServerConfig(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
- Assert.assertEquals(1, subject.getPrincipals().size());
- Assert.assertEquals(KerberosPrincipal.class,
- subject.getPrincipals().iterator().next().getClass());
- Assert.assertEquals(principal + "@" + kdc.getRealm(),
- subject.getPrincipals().iterator().next().getName());
+ assertEquals(1, subject.getPrincipals().size());
+ assertEquals(KerberosPrincipal.class, subject.getPrincipals().iterator().next().getClass());
+ assertEquals(principal + "@" + kdc.getRealm(), subject.getPrincipals().iterator().next().getName());
loginContext.logout();
} finally {
- if (loginContext != null && loginContext.getSubject() != null
- && !loginContext.getSubject().getPrincipals().isEmpty()) {
+ if (loginContext != null
+ && loginContext.getSubject() != null
+ && !loginContext.getSubject().getPrincipals().isEmpty()) {
loginContext.logout();
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java
index 8978d170f..db5d39da6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,19 +18,18 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase.MainThread;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,6 +38,7 @@ import org.slf4j.LoggerFactory;
* authentication using SASL mechanisms.
*/
public class QuorumAuthTestBase extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(QuorumAuthTestBase.class);
protected List<MainThread> mt = new ArrayList<MainThread>();
protected static File jaasConfigDir;
@@ -50,8 +50,7 @@ public class QuorumAuthTestBase extends ZKTestCase {
FileWriter fwriter = new FileWriter(saslConfFile);
fwriter.write(jaasEntries);
fwriter.close();
- System.setProperty("java.security.auth.login.config",
- saslConfFile.getAbsolutePath());
+ System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
} catch (IOException ioe) {
LOG.error("Failed to create tmp directory to hold JAAS conf file", ioe);
// could not create tmp directory to hold JAAS conf file : test will
@@ -65,28 +64,30 @@ public class QuorumAuthTestBase extends ZKTestCase {
}
}
- protected String startQuorum(final int serverCount,
- Map<String, String> authConfigs, int authServerCount) throws IOException {
+ protected String startQuorum(
+ final int serverCount,
+ Map<String, String> authConfigs,
+ int authServerCount) throws IOException {
StringBuilder connectStr = new StringBuilder();
- final int[] clientPorts = startQuorum(serverCount, connectStr,
- authConfigs, authServerCount);
+ final int[] clientPorts = startQuorum(serverCount, connectStr, authConfigs, authServerCount);
for (int i = 0; i < serverCount; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT));
}
return connectStr.toString();
}
- protected int[] startQuorum(final int serverCount, StringBuilder connectStr,
- Map<String, String> authConfigs, int authServerCount) throws IOException {
- final int clientPorts[] = new int[serverCount];
+ protected int[] startQuorum(
+ final int serverCount,
+ StringBuilder connectStr,
+ Map<String, String> authConfigs,
+ int authServerCount) throws IOException {
+ final int[] clientPorts = new int[serverCount];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < serverCount; i++) {
clientPorts[i] = PortAssignment.unique();
- String server = String.format(
- "server.%d=localhost:%d:%d:participant", i,
- PortAssignment.unique(), PortAssignment.unique());
+ String server = String.format("server.%d=localhost:%d:%d:participant", i, PortAssignment.unique(), PortAssignment.unique());
sb.append(server + "\n");
connectStr.append("127.0.0.1:" + clientPorts[i]);
if (i < serverCount - 1) {
@@ -108,20 +109,18 @@ public class QuorumAuthTestBase extends ZKTestCase {
return clientPorts;
}
- private void startServer(Map<String, String> authConfigs,
- final int[] clientPorts, String quorumCfg, int i)
- throws IOException {
- MainThread mthread = new MainThread(i, clientPorts[i], quorumCfg,
- authConfigs);
+ private void startServer(
+ Map<String, String> authConfigs,
+ final int[] clientPorts,
+ String quorumCfg,
+ int i) throws IOException {
+ MainThread mthread = new MainThread(i, clientPorts[i], quorumCfg, authConfigs);
mt.add(mthread);
mthread.start();
}
- protected void startServer(MainThread restartPeer,
- Map<String, String> authConfigs) throws IOException {
- MainThread mthread = new MainThread(restartPeer.getMyid(),
- restartPeer.getClientPort(), restartPeer.getQuorumCfgSection(),
- authConfigs);
+ protected void startServer(MainThread restartPeer, Map<String, String> authConfigs) throws IOException {
+ MainThread mthread = new MainThread(restartPeer.getMyid(), restartPeer.getClientPort(), restartPeer.getQuorumCfgSection(), authConfigs);
mt.add(mthread);
mthread.start();
}
@@ -137,10 +136,12 @@ public class QuorumAuthTestBase extends ZKTestCase {
try {
mainThread.shutdown();
} catch (InterruptedException e) {
+ // no op
} finally {
mt.remove(index);
}
mainThread.deleteBaseDir();
return mainThread;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java
index c54accadc..05f5a88d6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,22 +18,22 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase.MainThread;
import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ClientTest;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
+import org.apache.zookeeper.test.ClientTest;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Test;
/**
@@ -52,14 +52,17 @@ import org.junit.Test;
* Now, all the servers are fully upgraded and running in secured mode.
*/
public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
+
static {
- String jaasEntries = new String("" + "QuorumServer {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " user_test=\"mypassword\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " username=\"test\"\n"
- + " password=\"mypassword\";\n" + "};\n");
+ String jaasEntries = "QuorumServer {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_test=\"mypassword\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"test\"\n"
+ + " password=\"mypassword\";\n"
+ + "};\n";
setupJaasConfig(jaasEntries);
}
@@ -85,11 +88,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 0);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -105,11 +106,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 1);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -125,11 +124,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 2);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -147,11 +144,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 2);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -180,11 +175,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(3, authConfigs, 0);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//1. Upgrade peer0,1,2 with quorum.auth.enableSasl=true and
// quorum.auth.learnerRequireSasl=false, quorum.auth.serverRequireSasl=false
@@ -219,21 +212,24 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "false");
MainThread m = shutdown(2);
startServer(m, authConfigs);
- Assert.assertFalse("waiting for server 2 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + m.getClientPort(), 5000));
+ assertFalse(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + m.getClientPort(), 5000));
}
- private void restartServer(Map<String, String> authConfigs, int index,
- ZooKeeper zk, CountdownWatcher watcher) throws IOException,
- KeeperException, InterruptedException, TimeoutException {
+ private void restartServer(
+ Map<String, String> authConfigs,
+ int index,
+ ZooKeeper zk,
+ CountdownWatcher watcher) throws IOException, KeeperException, InterruptedException, TimeoutException {
LOG.info("Restarting server myid=" + index);
MainThread m = shutdown(index);
startServer(m, authConfigs);
- Assert.assertTrue("waiting for server" + index + "being up",
- ClientBase.waitForServerUp("127.0.0.1:" + m.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server" + index + "being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + m.getClientPort(), ClientBase.CONNECTION_TIMEOUT));
watcher.waitForConnected(ClientTest.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java
index 5eebdb335..ed86607c4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,41 +18,44 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.admin.AdminServer;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase.MainThread;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Test;
public class QuorumDigestAuthTest extends QuorumAuthTestBase {
static {
- String jaasEntries = new String(""
- + "QuorumServer {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " user_test=\"mypassword\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " username=\"test\"\n"
- + " password=\"mypassword\";\n" + "};\n"
- + "QuorumLearnerInvalid {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " username=\"test\"\n"
- + " password=\"invalid\";\n" + "};" + "\n");
+ String jaasEntries = "QuorumServer {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_test=\"mypassword\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"test\"\n"
+ + " password=\"mypassword\";\n"
+ + "};\n"
+ + "QuorumLearnerInvalid {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"test\"\n"
+ + " password=\"invalid\";\n"
+ + "};"
+ + "\n";
setupJaasConfig(jaasEntries);
}
@@ -65,7 +68,7 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
}
@AfterClass
- public static void cleanup(){
+ public static void cleanup() {
cleanupJaasConfig();
}
@@ -81,12 +84,10 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
String connectStr = startQuorum(3, authConfigs, 3);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
for (int i = 0; i < 10; i++) {
- zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
}
@@ -104,12 +105,10 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "false");
String connectStr = startQuorum(3, authConfigs, 3);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
for (int i = 0; i < 10; i++) {
- zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
}
@@ -127,13 +126,10 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "true");
authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, "true");
int serverCount = 2;
- final int[] clientPorts = startQuorum(serverCount, new StringBuilder(),
- authConfigs, serverCount);
+ final int[] clientPorts = startQuorum(serverCount, new StringBuilder(), authConfigs, serverCount);
for (int i = 0; i < serverCount; i++) {
- boolean waitForServerUp = ClientBase.waitForServerUp(
- "127.0.0.1:" + clientPorts[i], QuorumPeerTestBase.TIMEOUT);
- Assert.assertFalse("Shouldn't start server with invalid credentials",
- waitForServerUp);
+ boolean waitForServerUp = ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], QuorumPeerTestBase.TIMEOUT);
+ assertFalse("Shouldn't start server with invalid credentials", waitForServerUp);
}
}
@@ -143,62 +139,53 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
* enabled while enabling quorum server require sasl.
*/
@Test(timeout = 10000)
- public void testEnableQuorumServerRequireSaslWithoutQuorumLearnerRequireSasl()
- throws Exception {
+ public void testEnableQuorumServerRequireSaslWithoutQuorumLearnerRequireSasl() throws Exception {
Map<String, String> authConfigs = new HashMap<String, String>();
- authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
- "QuorumLearner");
+ authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearner");
authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "true");
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "true");
authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, "false");
- MainThread mthread = new MainThread(1, PortAssignment.unique(), "",
- authConfigs);
- String args[] = new String[1];
+ MainThread mthread = new MainThread(1, PortAssignment.unique(), "", authConfigs);
+ String[] args = new String[1];
args[0] = mthread.getConfFile().toString();
try {
new QuorumPeerMain() {
@Override
- protected void initializeAndRun(String[] args)
- throws ConfigException, IOException, AdminServer.AdminServerException {
+ protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServer.AdminServerException {
super.initializeAndRun(args);
}
}.initializeAndRun(args);
- Assert.fail("Must throw exception as quorumpeer learner is not enabled!");
+ fail("Must throw exception as quorumpeer learner is not enabled!");
} catch (ConfigException e) {
// expected
}
}
-
/**
* If quorumpeer learner is not auth enabled then self won't be able to join
* quorum. So this test is ensuring that the quorumpeer learner is also auth
* enabled while enabling quorum server require sasl.
*/
@Test(timeout = 10000)
- public void testEnableQuorumAuthenticationConfigurations()
- throws Exception {
+ public void testEnableQuorumAuthenticationConfigurations() throws Exception {
Map<String, String> authConfigs = new HashMap<String, String>();
- authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
- "QuorumLearner");
+ authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearner");
authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "false");
// case-1) 'quorum.auth.enableSasl' is off. Tries to enable server sasl.
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "true");
authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, "false");
- MainThread mthread = new MainThread(1, PortAssignment.unique(), "",
- authConfigs);
- String args[] = new String[1];
+ MainThread mthread = new MainThread(1, PortAssignment.unique(), "", authConfigs);
+ String[] args = new String[1];
args[0] = mthread.getConfFile().toString();
try {
new QuorumPeerMain() {
@Override
- protected void initializeAndRun(String[] args)
- throws ConfigException, IOException, AdminServer.AdminServerException {
+ protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServer.AdminServerException {
super.initializeAndRun(args);
}
}.initializeAndRun(args);
- Assert.fail("Must throw exception as quorum sasl is not enabled!");
+ fail("Must throw exception as quorum sasl is not enabled!");
} catch (ConfigException e) {
// expected
}
@@ -209,14 +196,14 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
try {
new QuorumPeerMain() {
@Override
- protected void initializeAndRun(String[] args)
- throws ConfigException, IOException, AdminServer.AdminServerException {
+ protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServer.AdminServerException {
super.initializeAndRun(args);
}
}.initializeAndRun(args);
- Assert.fail("Must throw exception as quorum sasl is not enabled!");
+ fail("Must throw exception as quorum sasl is not enabled!");
} catch (ConfigException e) {
// expected
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java
index 2cc56a767..092d04353 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -21,7 +21,6 @@ package org.apache.zookeeper.server.quorum.auth;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.zookeeper.CreateMode;
@@ -36,26 +35,38 @@ import org.junit.Before;
import org.junit.Test;
public class QuorumKerberosAuthTest extends KerberosSecurityTestcase {
+
private static File keytabFile;
+
static {
String keytabFilePath = FilenameUtils.normalize(KerberosTestUtils.getKeytabFile(), true);
- String jaasEntries = new String(""
- + "QuorumServer {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.getServerPrincipal() + "\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.getLearnerPrincipal() + "\";\n" + "};\n");
+ String jaasEntries = ""
+ + "QuorumServer {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\""
+ + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\""
+ + KerberosTestUtils.getServerPrincipal()
+ + "\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\""
+ + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\""
+ + KerberosTestUtils.getLearnerPrincipal()
+ + "\";\n"
+ + "};\n";
setupJaasConfig(jaasEntries);
}
@@ -80,7 +91,7 @@ public class QuorumKerberosAuthTest extends KerberosSecurityTestcase {
@AfterClass
public static void cleanup() {
- if(keytabFile != null){
+ if (keytabFile != null) {
FileUtils.deleteQuietly(keytabFile);
}
cleanupJaasConfig();
@@ -107,4 +118,5 @@ public class QuorumKerberosAuthTest extends KerberosSecurityTestcase {
}
zk.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java
index b38462b04..574bfe4ee 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,11 +18,11 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.fail;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.zookeeper.CreateMode;
@@ -34,47 +34,58 @@ import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
+
private static File keytabFile;
private static String hostServerPrincipal = KerberosTestUtils.getHostServerPrincipal();
private static String hostLearnerPrincipal = KerberosTestUtils.getHostLearnerPrincipal();
private static String hostNamedLearnerPrincipal = KerberosTestUtils.getHostNamedLearnerPrincipal("myHost");
+
static {
setupJaasConfigEntries(hostServerPrincipal, hostLearnerPrincipal, hostNamedLearnerPrincipal);
}
- private static void setupJaasConfigEntries(String hostServerPrincipal,
- String hostLearnerPrincipal, String hostNamedLearnerPrincipal) {
+ private static void setupJaasConfigEntries(
+ String hostServerPrincipal,
+ String hostLearnerPrincipal,
+ String hostNamedLearnerPrincipal) {
String keytabFilePath = FilenameUtils.normalize(KerberosTestUtils.getKeytabFile(), true);
- String jaasEntries = new String(""
- + "QuorumServer {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostServerPrincipal) + "\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostLearnerPrincipal) + "\";\n" + "};\n"
- + "QuorumLearnerMyHost {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + hostNamedLearnerPrincipal + "\";\n" + "};\n");
+ String jaasEntries = "QuorumServer {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\"" + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostServerPrincipal)
+ + "\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\"" + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostLearnerPrincipal)
+ + "\";\n"
+ + "};\n"
+ + "QuorumLearnerMyHost {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\"" + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\"" + hostNamedLearnerPrincipal
+ + "\";\n"
+ + "};\n";
setupJaasConfig(jaasEntries);
}
@@ -104,7 +115,7 @@ public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
@AfterClass
public static void cleanup() {
- if(keytabFile != null){
+ if (keytabFile != null) {
FileUtils.deleteQuietly(keytabFile);
}
cleanupJaasConfig();
@@ -157,22 +168,19 @@ public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
int myid = mt.size() + 1;
final int clientPort = PortAssignment.unique();
- String server = String.format("server.%d=localhost:%d:%d:participant",
- myid, PortAssignment.unique(), PortAssignment.unique());
+ String server = String.format("server.%d=localhost:%d:%d:participant", myid, PortAssignment.unique(), PortAssignment.unique());
sb.append(server + "\n");
quorumCfgSection = sb.toString();
- authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
- "QuorumLearnerMyHost");
- MainThread badServer = new MainThread(myid, clientPort, quorumCfgSection,
- authConfigs);
+ authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearnerMyHost");
+ MainThread badServer = new MainThread(myid, clientPort, quorumCfgSection, authConfigs);
badServer.start();
watcher = new CountdownWatcher();
connectStr = "127.0.0.1:" + clientPort;
zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
- try{
- watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT/3);
- Assert.fail("Must throw exception as the myHost is not an authorized one!");
- } catch (TimeoutException e){
+ try {
+ watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT / 3);
+ fail("Must throw exception as the myHost is not an authorized one!");
+ } catch (TimeoutException e) {
// expected
} finally {
zk.close();
@@ -180,4 +188,5 @@ public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
badServer.deleteBaseDir();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java
index 1af5f29dc..e88301199 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,15 +18,13 @@
package org.apache.zookeeper.server.util;
-import org.apache.zookeeper.ZKTestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
-
-import org.junit.Test;
-
+import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class AdHashTest extends ZKTestCase {
@@ -42,13 +40,13 @@ public class AdHashTest extends ZKTestCase {
}
private static void addListOfDigests(AdHash hash, List<Long> digests) {
- for (long b: digests) {
+ for (long b : digests) {
hash.addDigest(b);
}
}
private static void removeListOfDigests(AdHash hash, List<Long> digests) {
- for (long b: digests) {
+ for (long b : digests) {
hash.removeDigest(b);
}
}
@@ -57,7 +55,7 @@ public class AdHashTest extends ZKTestCase {
* Test thhe add and remove digest from AdHash is working as expected.
*/
@Test
- public void testAdHash() throws Exception{
+ public void testAdHash() throws Exception {
List<Long> bucket1 = generateRandomHashes(50);
List<Long> bucket2 = generateRandomHashes(3);
List<Long> bucket3 = generateRandomHashes(30);
@@ -72,7 +70,7 @@ public class AdHashTest extends ZKTestCase {
AdHash hash21 = new AdHash();
addListOfDigests(hash21, bucket2);
addListOfDigests(hash21, bucket1);
- Assert.assertEquals(hash12, hash21);
+ assertEquals(hash12, hash21);
AdHash hashall = new AdHash();
addListOfDigests(hashall, bucket1);
@@ -80,17 +78,16 @@ public class AdHashTest extends ZKTestCase {
addListOfDigests(hashall, bucket3);
addListOfDigests(hashall, bucket4);
addListOfDigests(hashall, bucket5);
- Assert.assertFalse("digest of different set not different", hashall.equals(hash21));
+ assertFalse("digest of different set not different", hashall.equals(hash21));
removeListOfDigests(hashall, bucket4);
removeListOfDigests(hashall, bucket5);
addListOfDigests(hash21, bucket3);
- Assert.assertEquals("hashall with 4 & 5 removed should match hash21 with 3 added",
- hashall, hash21);
+ assertEquals("hashall with 4 & 5 removed should match hash21 with 3 added", hashall, hash21);
removeListOfDigests(hashall, bucket3);
removeListOfDigests(hashall, bucket2);
removeListOfDigests(hashall, bucket1);
- Assert.assertEquals("empty hashall's digest should be 0", hashall.toHexString(), "0");
+ assertEquals("empty hashall's digest should be 0", hashall.toHexString(), "0");
AdHash hash45 = new AdHash();
addListOfDigests(hash45, bucket4);
@@ -98,6 +95,7 @@ public class AdHashTest extends ZKTestCase {
addListOfDigests(hashall, bucket4);
addListOfDigests(hashall, bucket5);
- Assert.assertEquals("empty hashall + 4&5 should equal hash45", hashall, hash45);
+ assertEquals("empty hashall + 4&5 should equal hash45", hashall, hash45);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java
index a70eaa526..ff67c4e66 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java
@@ -14,16 +14,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.util;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.List;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
-
+import java.util.List;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class BitHashSetTest extends ZKTestCase {
@@ -31,38 +32,34 @@ public class BitHashSetTest extends ZKTestCase {
public void testAddWatchBit() {
int watcherCacheSize = 1;
BitHashSet ws = new BitHashSet(watcherCacheSize);
- Assert.assertTrue(ws.add(1));
- Assert.assertEquals(1, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertTrue(ws.add(1));
+ assertEquals(1, ws.size());
+ assertEquals(1, ws.cachedSize());
List<Integer> actualBits = new ArrayList<Integer>();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {1},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{1}, actualBits.toArray(new Integer[actualBits.size()]));
// add the same bit again
- Assert.assertFalse(ws.add(1));
- Assert.assertEquals(1, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertFalse(ws.add(1));
+ assertEquals(1, ws.size());
+ assertEquals(1, ws.cachedSize());
// add another bit, make sure there there is only 1 bit cached
- Assert.assertTrue(ws.add(2));
- Assert.assertEquals(2, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertTrue(ws.add(2));
+ assertEquals(2, ws.size());
+ assertEquals(1, ws.cachedSize());
- Assert.assertTrue(ws.contains(1));
+ assertTrue(ws.contains(1));
actualBits.clear();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {1, 2},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{1, 2}, actualBits.toArray(new Integer[actualBits.size()]));
}
@Test
@@ -72,39 +69,36 @@ public class BitHashSetTest extends ZKTestCase {
ws.add(1);
ws.add(2);
- Assert.assertTrue(ws.contains(1));
- Assert.assertTrue(ws.contains(2));
+ assertTrue(ws.contains(1));
+ assertTrue(ws.contains(2));
ws.remove(1);
- Assert.assertFalse(ws.contains(1));
- Assert.assertEquals(1, ws.size());
- Assert.assertEquals(0, ws.cachedSize());
+ assertFalse(ws.contains(1));
+ assertEquals(1, ws.size());
+ assertEquals(0, ws.cachedSize());
List<Integer> actualBits = new ArrayList<Integer>();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {2},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{2}, actualBits.toArray(new Integer[actualBits.size()]));
ws.add(3);
- Assert.assertEquals(2, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertEquals(2, ws.size());
+ assertEquals(1, ws.cachedSize());
actualBits.clear();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {2, 3},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{2, 3}, actualBits.toArray(new Integer[actualBits.size()]));
ws.remove(2);
ws.remove(3);
- Assert.assertEquals(0, ws.size());
- Assert.assertEquals(0, ws.cachedSize());
+ assertEquals(0, ws.size());
+ assertEquals(0, ws.cachedSize());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java
index eca0f2d25..799a78662 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java
@@ -14,46 +14,50 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.util;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class BitMapTest extends ZKTestCase {
@Test
public void testAddAndRemove() {
BitMap<String> bitMap = new BitMap<String>();
- String v1 = new String("v1");
+ String v1 = "v1";
Integer bit = bitMap.add(v1);
- Assert.assertEquals(1, bitMap.size());
- Assert.assertTrue(bit >= 0);
- Assert.assertEquals(v1, bitMap.get(bit));
- Assert.assertEquals(bit, bitMap.getBit(v1));
+ assertEquals(1, bitMap.size());
+ assertTrue(bit >= 0);
+ assertEquals(v1, bitMap.get(bit));
+ assertEquals(bit, bitMap.getBit(v1));
// add the same value again
Integer newBit = bitMap.add(v1);
- Assert.assertEquals(bit, newBit);
- Assert.assertEquals(1, bitMap.size());
+ assertEquals(bit, newBit);
+ assertEquals(1, bitMap.size());
- String v2 = new String("v2");
+ String v2 = "v2";
Integer v2Bit = bitMap.add(v2);
- Assert.assertEquals(2, bitMap.size());
- Assert.assertNotEquals(v2Bit, bit);
+ assertEquals(2, bitMap.size());
+ assertNotEquals(v2Bit, bit);
// remove by value
bitMap.remove(v1);
- Assert.assertEquals(1, bitMap.size());
- Assert.assertNull(bitMap.get(bit));
- Assert.assertNull(bitMap.getBit(v1));
+ assertEquals(1, bitMap.size());
+ assertNull(bitMap.get(bit));
+ assertNull(bitMap.getBit(v1));
// remove by bit
bitMap.remove(v2Bit);
- Assert.assertEquals(0, bitMap.size());
- Assert.assertNull(bitMap.get(v2Bit));
- Assert.assertNull(bitMap.getBit(v2));
+ assertEquals(0, bitMap.size());
+ assertNull(bitMap.get(v2Bit));
+ assertNull(bitMap.getBit(v2));
}
@Test
@@ -66,6 +70,7 @@ public class BitMapTest extends ZKTestCase {
int v4Bit = bitMap.add("v4");
- Assert.assertEquals(v4Bit, v2Bit);
+ assertEquals(v4Bit, v2Bit);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java
index 41c450d8c..ba68b229e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,9 +18,9 @@
package org.apache.zookeeper.server.util;
-import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
+import org.junit.Test;
public class ConfigUtilsTest {
@@ -29,7 +29,7 @@ public class ConfigUtilsTest {
String[] nsa = ConfigUtils.getHostAndPort("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443");
assertEquals(nsa[0], "2001:db8:85a3:8d3:1319:8a2e:370:7348");
assertEquals(nsa[1], "443");
-
+
nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]:2888:3888");
assertEquals(nsa[0], "2001:db8:1::242:ac11:2");
assertEquals(nsa[1], "2888");
@@ -41,7 +41,7 @@ public class ConfigUtilsTest {
String[] nsa = ConfigUtils.getHostAndPort("127.0.0.1:443");
assertEquals(nsa[0], "127.0.0.1");
assertEquals(nsa[1], "443");
-
+
nsa = ConfigUtils.getHostAndPort("127.0.0.1:2888:3888");
assertEquals(nsa[0], "127.0.0.1");
assertEquals(nsa[1], "2888");
@@ -52,21 +52,21 @@ public class ConfigUtilsTest {
public void testGetHostAndPortWithoutBracket() throws ConfigException {
String[] nsa = ConfigUtils.getHostAndPort("[2001:db8:85a3:8d3:1319:8a2e:370:7348");
}
-
+
@Test(expected = ConfigException.class)
public void testGetHostAndPortWithoutPortAfterColon() throws ConfigException {
String[] nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]:");
}
-
+
@Test
public void testGetHostAndPortWithoutPort() throws ConfigException {
- String[] nsa = ConfigUtils.getHostAndPort("127.0.0.1");
- assertEquals(nsa[0], "127.0.0.1");
- assertEquals(nsa.length, 1);
-
- nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]");
- assertEquals(nsa[0], "2001:db8:1::242:ac11:2");
- assertEquals(nsa.length, 1);
+ String[] nsa = ConfigUtils.getHostAndPort("127.0.0.1");
+ assertEquals(nsa[0], "127.0.0.1");
+ assertEquals(nsa.length, 1);
+
+ nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]");
+ assertEquals(nsa[0], "2001:db8:1::242:ac11:2");
+ assertEquals(nsa.length, 1);
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java
index 4e701b83d..58b1902a2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,14 +18,13 @@
package org.apache.zookeeper.server.util;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class JvmPauseMonitorTest {
private final Long sleepTime = 100L;
@@ -33,7 +32,7 @@ public class JvmPauseMonitorTest {
private final Long warnTH = -1L;
private JvmPauseMonitor pauseMonitor;
- @Test(timeout=5000)
+ @Test(timeout = 5000)
public void testJvmPauseMonitorExceedInfoThreshold() throws InterruptedException {
QuorumPeerConfig qpConfig = mock(QuorumPeerConfig.class);
when(qpConfig.getJvmPauseSleepTimeMs()).thenReturn(sleepTime);
@@ -42,15 +41,15 @@ public class JvmPauseMonitorTest {
pauseMonitor = new JvmPauseMonitor(qpConfig);
pauseMonitor.serviceStart();
- Assert.assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
- Assert.assertEquals(infoTH, Long.valueOf(pauseMonitor.infoThresholdMs));
+ assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
+ assertEquals(infoTH, Long.valueOf(pauseMonitor.infoThresholdMs));
- while(pauseMonitor.getNumGcInfoThresholdExceeded() == 0) {
+ while (pauseMonitor.getNumGcInfoThresholdExceeded() == 0) {
Thread.sleep(200);
}
}
- @Test(timeout=5000)
+ @Test(timeout = 5000)
public void testJvmPauseMonitorExceedWarnThreshold() throws InterruptedException {
QuorumPeerConfig qpConfig = mock(QuorumPeerConfig.class);
when(qpConfig.getJvmPauseSleepTimeMs()).thenReturn(sleepTime);
@@ -59,10 +58,10 @@ public class JvmPauseMonitorTest {
pauseMonitor = new JvmPauseMonitor(qpConfig);
pauseMonitor.serviceStart();
- Assert.assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
- Assert.assertEquals(warnTH, Long.valueOf(pauseMonitor.warnThresholdMs));
+ assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
+ assertEquals(warnTH, Long.valueOf(pauseMonitor.warnThresholdMs));
- while(pauseMonitor.getNumGcWarnThresholdExceeded() == 0) {
+ while (pauseMonitor.getNumGcWarnThresholdExceeded() == 0) {
Thread.sleep(200);
}
@@ -72,4 +71,5 @@ public class JvmPauseMonitorTest {
public void teardown() {
pauseMonitor.serviceStop();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java
index 84868498c..c66dcc869 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -31,7 +31,6 @@ import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,15 +38,15 @@ import org.slf4j.LoggerFactory;
* A utility that does bi-directional forwarding between two ports.
* Useful, for example, to simulate network failures.
* Example:
- *
+ *
* Server 1 config file:
- *
+ *
* server.1=127.0.0.1:7301:7401;8201
* server.2=127.0.0.1:7302:7402;8202
* server.3=127.0.0.1:7303:7403;8203
- *
+ *
* Server 2 and 3 config files:
- *
+ *
* server.1=127.0.0.1:8301:8401;8201
* server.2=127.0.0.1:8302:8402;8202
* server.3=127.0.0.1:8303:8403;8203
@@ -55,13 +54,13 @@ import org.slf4j.LoggerFactory;
* Initially forward traffic between 730x and 830x and between 740x and 830x
* This way server 1 can communicate with servers 2 and 3
* ....
- *
+ *
* List&lt;PortForwarder&gt; pfs = startForwarding();
* ....
* // simulate a network interruption for server 1
* stopForwarding(pfs);
* ....
- * // restore connection
+ * // restore connection
* pfs = startForwarding();
*
*
@@ -75,18 +74,18 @@ import org.slf4j.LoggerFactory;
* res.add(new PortForwarder(7403, 8403));
* return res;
* }
- *
+ *
* private void stopForwarding(List&lt;PortForwarder&gt; pfs) throws Exception {
* for (PortForwarder pf : pfs) {
* pf.shutdown();
* }
* }
- *
+ *
*
*/
public class PortForwarder extends Thread {
- private static final Logger LOG = LoggerFactory
- .getLogger(PortForwarder.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(PortForwarder.class);
private static class PortForwardWorker implements Runnable {
@@ -96,8 +95,7 @@ public class PortForwarder extends Thread {
private final Socket toClose2;
private boolean isFinished = false;
- PortForwardWorker(Socket toClose, Socket toClose2, InputStream in,
- OutputStream out) {
+ PortForwardWorker(Socket toClose, Socket toClose2, InputStream in, OutputStream out) {
this.toClose = toClose;
this.toClose2 = toClose2;
this.in = in;
@@ -106,8 +104,7 @@ public class PortForwarder extends Thread {
}
public void run() {
- Thread.currentThread().setName(toClose.toString() + "-->"
- + toClose2.toString());
+ Thread.currentThread().setName(toClose.toString() + "-->" + toClose2.toString());
byte[] buf = new byte[1024];
try {
while (true) {
@@ -146,7 +143,7 @@ public class PortForwarder extends Thread {
boolean waitForShutdown(long timeoutMs) throws InterruptedException {
synchronized (this) {
if (!isFinished) {
- this.wait(timeoutMs);
+ this.wait(timeoutMs);
}
}
return isFinished;
@@ -164,6 +161,7 @@ public class PortForwarder extends Thread {
// ignore silently
}
}
+
}
private volatile boolean stopped = false;
@@ -185,56 +183,58 @@ public class PortForwarder extends Thread {
while (!stopped) {
Socket sock = null;
try {
- LOG.info("accepting socket local:"
- + serverSocket.getLocalPort() + " to:" + to);
+ LOG.info("accepting socket local:" + serverSocket.getLocalPort() + " to:" + to);
sock = serverSocket.accept();
- LOG.info("accepted: local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to);
+ LOG.info("accepted: local:" + sock.getLocalPort() + " from:" + sock.getPort() + " to:" + to);
Socket target = null;
int retry = 10;
- while(sock.isConnected()) {
+ while (sock.isConnected()) {
try {
target = new Socket("localhost", to);
break;
} catch (IOException e) {
if (retry == 0) {
- throw e;
+ throw e;
}
- LOG.warn("connection failed, retrying(" + retry
- + "): local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to, e);
+ LOG.warn("connection failed, retrying("
+ + retry
+ + "): local:"
+ + sock.getLocalPort()
+ + " from:"
+ + sock.getPort()
+ + " to:"
+ + to, e);
}
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
retry--;
}
- LOG.info("connected: local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to);
+ LOG.info("connected: local:" + sock.getLocalPort() + " from:" + sock.getPort() + " to:" + to);
sock.setSoTimeout(30000);
target.setSoTimeout(30000);
-
- workers.add(new PortForwardWorker(sock, target,
- sock.getInputStream(), target.getOutputStream()));
- workers.add(new PortForwardWorker(target, sock,
- target.getInputStream(), sock.getOutputStream()));
- for (PortForwardWorker worker: workers) {
+ workers.add(new PortForwardWorker(sock, target, sock.getInputStream(), target.getOutputStream()));
+ workers.add(new PortForwardWorker(target, sock, target.getInputStream(), sock.getOutputStream()));
+ for (PortForwardWorker worker : workers) {
workerExecutor.submit(worker);
}
} catch (SocketTimeoutException e) {
LOG.warn("socket timed out", e);
} catch (ConnectException e) {
- LOG.warn("connection exception local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to, e);
+ LOG.warn("connection exception local:"
+ + sock.getLocalPort()
+ + " from:"
+ + sock.getPort()
+ + " to:"
+ + to, e);
sock.close();
} catch (IOException e) {
if (!"Socket closed".equals(e.getMessage())) {
- LOG.warn("unexpected exception local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to, e);
+ LOG.warn("unexpected exception local:"
+ + sock.getLocalPort()
+ + " from:"
+ + sock.getPort()
+ + " to:"
+ + to, e);
throw e;
}
}
@@ -252,14 +252,15 @@ public class PortForwarder extends Thread {
this.serverSocket.close();
this.join();
this.workerExecutor.shutdownNow();
- for (PortForwardWorker worker: workers) {
+ for (PortForwardWorker worker : workers) {
worker.shutdown();
}
- for (PortForwardWorker worker: workers) {
+ for (PortForwardWorker worker : workers) {
if (!worker.waitForShutdown(5000)) {
throw new Exception("Failed to stop forwarding within 5 seconds");
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java
index 7440b193c..ecfc92c00 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,18 +18,6 @@
package org.apache.zookeeper.server.util;
-import java.util.Map;
-import java.util.Random;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-import org.junit.Before;
-import org.junit.After;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.Assert;
-
import static org.apache.zookeeper.ZooDefs.OpCode.create;
import static org.apache.zookeeper.ZooDefs.OpCode.create2;
import static org.apache.zookeeper.ZooDefs.OpCode.delete;
@@ -38,6 +26,17 @@ import static org.apache.zookeeper.ZooDefs.OpCode.getChildren;
import static org.apache.zookeeper.ZooDefs.OpCode.getChildren2;
import static org.apache.zookeeper.ZooDefs.OpCode.getData;
import static org.apache.zookeeper.ZooDefs.OpCode.setData;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
public class RequestPathMetricsCollectorTest {
@@ -63,366 +62,355 @@ public class RequestPathMetricsCollectorTest {
public void testTrimPath() {
//normal cases
String trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 1);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1"));
trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 2);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1/p2"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1/p2"));
trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 3);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 4);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
//some extra symbols
- trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next",
- 3);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
- trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next",
- 2);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index"));
- trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next",
- 6);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
+ trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next", 3);
+ assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
+ trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next", 2);
+ assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index"));
+ trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next", 6);
+ assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
}
@Test
public void testQueueMapReduce() throws InterruptedException {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector();
- RequestPathMetricsCollector.PathStatsQueue pathStatsQueue =
- requestPathMetricsCollector.new PathStatsQueue(create2);
+ RequestPathMetricsCollector.PathStatsQueue pathStatsQueue = requestPathMetricsCollector.new PathStatsQueue(create2);
Thread path7 = new Thread(() -> {
for (int i = 0; i < 1000000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7" +
- "_" + i);
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7" + "_" + i);
}
});
path7.start();
Thread path6 = new Thread(() -> {
pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6");
- for(int i = 1; i < 100000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6"+"_"+i);
+ for (int i = 1; i < 100000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6" + "_" + i);
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
+ for (int i = 0; i < 1; i++) {
pathStatsQueue.registerRequest("/path1");
}
- for(int i = 0; i < 10; i++) {
- pathStatsQueue.registerRequest("/path1/path2"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ pathStatsQueue.registerRequest("/path1/path2" + "_" + i);
}
- for(int i = 0; i < 100; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 100; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4" + "_" + i);
}
- for(int i = 0; i < 10000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
- Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(1,
- pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 1);
- Assert.assertTrue(newSlot.get("/path1").compareTo(1111111) == 0);
+ Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(1, pathStatsQueue.getCurrentSlot());
+ assertTrue(newSlot.size() == 1);
+ assertTrue(newSlot.get("/path1").compareTo(1111111) == 0);
//cut up to 2
newSlot = pathStatsQueue.mapReducePaths(2, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 12);
- Assert.assertTrue(newSlot.get("/path1").compareTo(1) == 0);
- Assert.assertTrue(newSlot.get("/path1/path2").compareTo(1111100) == 0);
+ assertTrue(newSlot.size() == 12);
+ assertTrue(newSlot.get("/path1").compareTo(1) == 0);
+ assertTrue(newSlot.get("/path1/path2").compareTo(1111100) == 0);
//cut up to 3
newSlot = pathStatsQueue.mapReducePaths(3, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 112);
- Assert.assertTrue(newSlot.get("/path1").compareTo(1) == 0);
- Assert.assertTrue(newSlot.get("/path1/path2/path3").compareTo(1111000) == 0);
+ assertTrue(newSlot.size() == 112);
+ assertTrue(newSlot.get("/path1").compareTo(1) == 0);
+ assertTrue(newSlot.get("/path1/path2/path3").compareTo(1111000) == 0);
//cut up to 4
newSlot = pathStatsQueue.mapReducePaths(4, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 1112);
- Assert.assertTrue(newSlot.get("/path1/path2/path3/path4").compareTo(1110000) == 0);
+ assertTrue(newSlot.size() == 1112);
+ assertTrue(newSlot.get("/path1/path2/path3/path4").compareTo(1110000) == 0);
//cut up to 5
newSlot = pathStatsQueue.mapReducePaths(5, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 11112);
- Assert.assertTrue(newSlot.get("/path1/path2/path3/path4/path5").compareTo(1100000) == 0);
+ assertTrue(newSlot.size() == 11112);
+ assertTrue(newSlot.get("/path1/path2/path3/path4/path5").compareTo(1100000) == 0);
//cut up to 6
newSlot = pathStatsQueue.mapReducePaths(6, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 111111);
- Assert.assertTrue(newSlot.get("/path1/path2/path3/path4/path5/path6").compareTo(1000001) == 0);
+ assertTrue(newSlot.size() == 111111);
+ assertTrue(newSlot.get("/path1/path2/path3/path4/path5/path6").compareTo(1000001) == 0);
//cut up to 7
newSlot = pathStatsQueue.mapReducePaths(7, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 1111111);
+ assertTrue(newSlot.size() == 1111111);
}
@Test
public void testCollectEmptyStats() throws InterruptedException {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector();
- RequestPathMetricsCollector.PathStatsQueue pathStatsQueue =
- requestPathMetricsCollector.new PathStatsQueue(getChildren);
+ RequestPathMetricsCollector.PathStatsQueue pathStatsQueue = requestPathMetricsCollector.new PathStatsQueue(getChildren);
Thread.sleep(5000);
- Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(3,
- pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.isEmpty());
+ Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(3, pathStatsQueue.getCurrentSlot());
+ assertTrue(newSlot.isEmpty());
pathStatsQueue.start();
Thread.sleep(15000);
newSlot = pathStatsQueue.collectStats(1);
- Assert.assertTrue(newSlot.size() == 0);
+ assertTrue(newSlot.size() == 0);
newSlot = pathStatsQueue.collectStats(2);
- Assert.assertTrue(newSlot.size() == 0);
+ assertTrue(newSlot.size() == 0);
newSlot = pathStatsQueue.collectStats(5);
- Assert.assertTrue(newSlot.size() == 0);
+ assertTrue(newSlot.size() == 0);
}
@Test
@Ignore
public void testCollectStats() throws InterruptedException {
- RequestPathMetricsCollector requestPathMetricsCollector =
- new RequestPathMetricsCollector(true);
- RequestPathMetricsCollector.PathStatsQueue pathStatsQueue =
- requestPathMetricsCollector.new PathStatsQueue(getChildren);
+ RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector(true);
+ RequestPathMetricsCollector.PathStatsQueue pathStatsQueue = requestPathMetricsCollector.new PathStatsQueue(getChildren);
pathStatsQueue.start();
Thread path7 = new Thread(() -> {
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100000; j++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7"
- + "_" + i + "_" + j);
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7" + "_" + i + "_" + j);
}
}
});
path7.start();
Thread path6 = new Thread(() -> {
pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6");
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6"
- + "_" + i + "_" + j);
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6" + "_" + i + "_" + j);
}
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
+ for (int i = 0; i < 1; i++) {
pathStatsQueue.registerRequest("/path1");
- }
- for(int i = 0; i < 10; i++) {
- pathStatsQueue.registerRequest("/path1/path2"+"_"+i);
}
- for(int i = 0; i < 100; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ pathStatsQueue.registerRequest("/path1/path2" + "_" + i);
+ }
+ for (int i = 0; i < 100; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4" + "_" + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
- for(int i = 0; i < 10000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
Map<String, Integer> newSlot = pathStatsQueue.collectStats(1);
- Assert.assertEquals(newSlot.size(), 1);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1111112);
+ assertEquals(newSlot.size(), 1);
+ assertEquals(newSlot.get("/path1").intValue(), 1111112);
//cut up to 2
newSlot = pathStatsQueue.collectStats(2);
- Assert.assertEquals(newSlot.size(), 12);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
+ assertEquals(newSlot.size(), 12);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
//cut up to 3
newSlot = pathStatsQueue.collectStats(3);
- Assert.assertEquals(newSlot.size(), 112);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
+ assertEquals(newSlot.size(), 112);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
//cut up to 4
newSlot = pathStatsQueue.collectStats(4);
- Assert.assertEquals(newSlot.size(), 1112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
+ assertEquals(newSlot.size(), 1112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
//cut up to 5
newSlot = pathStatsQueue.collectStats(5);
- Assert.assertEquals(newSlot.size(), 11112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
+ assertEquals(newSlot.size(), 11112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
//cut up to 6
newSlot = pathStatsQueue.collectStats(6);
- Assert.assertEquals(newSlot.size(), 111112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(),
- 1000001);
+ assertEquals(newSlot.size(), 111112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
}
-
+
@Test
public void testAggregate() throws InterruptedException {
- RequestPathMetricsCollector requestPathMetricsCollector =
- new RequestPathMetricsCollector(true);
+ RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector(true);
Thread path7 = new Thread(() -> {
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100000; j++) {
- requestPathMetricsCollector.registerRequest(getData,
- "/path1/path2/path3/path4/path5/path6/path7" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getData, "/path1/path2/path3/path4/path5/path6/path7"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path7.start();
Thread path6 = new Thread(() -> {
- requestPathMetricsCollector.registerRequest(getChildren2,
- "/path1/path2/path3/path4/path5/path6");
- for(int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(getChildren2, "/path1/path2/path3/path4/path5/path6");
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
- requestPathMetricsCollector.registerRequest(getChildren,
- "/path1/path2/path3/path4/path5/path6" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getChildren, "/path1/path2/path3/path4/path5/path6"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
- requestPathMetricsCollector.registerRequest(create2,
- "/path1");
+ for (int i = 0; i < 1; i++) {
+ requestPathMetricsCollector.registerRequest(create2, "/path1");
}
- for(int i = 0; i < 10; i++) {
- requestPathMetricsCollector.registerRequest(create,
- "/path1/path2"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(create, "/path1/path2" + "_" + i);
}
- for(int i = 0; i < 100; i++) {
- requestPathMetricsCollector.registerRequest(delete,
- "/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 100; i++) {
+ requestPathMetricsCollector.registerRequest(delete, "/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- requestPathMetricsCollector.registerRequest(setData,
- "/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ requestPathMetricsCollector.registerRequest(setData, "/path1/path2/path3/path4" + "_" + i);
}
- for(int i = 0; i < 10000; i++) {
- requestPathMetricsCollector.registerRequest(exists,
- "/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ requestPathMetricsCollector.registerRequest(exists, "/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
- Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(2,
- queue -> true);
- Assert.assertEquals(newSlot.size(), 12);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
+ Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(2, queue -> true);
+ assertEquals(newSlot.size(), 12);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
//cut up to 3
newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> true);
- Assert.assertEquals(newSlot.size(), 112);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
+ assertEquals(newSlot.size(), 112);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
//cut up to 4
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> true);
- Assert.assertEquals(newSlot.size(), 1112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
+ assertEquals(newSlot.size(), 1112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
//cut up to 5
newSlot = requestPathMetricsCollector.aggregatePaths(5, queue -> true);
- Assert.assertEquals(newSlot.size(), 11112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
+ assertEquals(newSlot.size(), 11112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
//cut up to 6
newSlot = requestPathMetricsCollector.aggregatePaths(6, queue -> true);
- Assert.assertEquals(newSlot.size(), 111112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
+ assertEquals(newSlot.size(), 111112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
//cut up to 7 but the initial mapReduce kept only 6
newSlot = requestPathMetricsCollector.aggregatePaths(7, queue -> true);
- Assert.assertEquals(newSlot.size(), 111112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
+ assertEquals(newSlot.size(), 111112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
//test predicate
//cut up to 4 for all the reads
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> !queue.isWriteOperation());
- Assert.assertEquals(newSlot.size(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
+ assertEquals(newSlot.size(), 1);
+ assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
//cut up to 4 for all the write
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> queue.isWriteOperation());
- Assert.assertEquals(newSlot.size(), 1111);
+ assertEquals(newSlot.size(), 1111);
//cut up to 3 for all the write
newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> queue.isWriteOperation());
- Assert.assertEquals(newSlot.size(), 112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1000);
+ assertEquals(newSlot.size(), 112);
+ assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1000);
}
@Test
public void testTopPath() throws InterruptedException {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector(true);
Thread path7 = new Thread(() -> {
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100000; j++) {
- requestPathMetricsCollector.registerRequest(getData,
- "/path1/path2/path3/path4/path5/path6/path7" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getData, "/path1/path2/path3/path4/path5/path6/path7"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path7.start();
Thread path6 = new Thread(() -> {
- requestPathMetricsCollector.registerRequest(getChildren2,
- "/path1/path2/path3/path4/path5/path6");
- for(int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(getChildren2, "/path1/path2/path3/path4/path5/path6");
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
- requestPathMetricsCollector.registerRequest(getChildren,
- "/path1/path2/path3/path4/path5/path6" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getChildren, "/path1/path2/path3/path4/path5/path6"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
- requestPathMetricsCollector.registerRequest(create2,
- "/path1");
+ for (int i = 0; i < 1; i++) {
+ requestPathMetricsCollector.registerRequest(create2, "/path1");
}
- for(int i = 0; i < 10; i++) {
- requestPathMetricsCollector.registerRequest(create,
- "/path1/path2"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(create, "/path1/path2" + "_" + i);
}
- for(int i = 0; i < 100; i++) {
- requestPathMetricsCollector.registerRequest(delete,
- "/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 100; i++) {
+ requestPathMetricsCollector.registerRequest(delete, "/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- requestPathMetricsCollector.registerRequest(setData,
- "/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ requestPathMetricsCollector.registerRequest(setData, "/path1/path2/path3/path4" + "_" + i);
}
- for(int i = 0; i < 10000; i++) {
- requestPathMetricsCollector.registerRequest(exists,
- "/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ requestPathMetricsCollector.registerRequest(exists, "/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
- StringBuilder sb1= new StringBuilder();
- Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(3,
- queue -> queue.isWriteOperation());
- requestPathMetricsCollector.logTopPaths(newSlot,
- entry -> sb1.append(entry.getKey() + " : " + entry.getValue() + "\n"));
- Assert.assertTrue(sb1.toString().startsWith("/path1/path2/path3 : 1000"));
- StringBuilder sb2= new StringBuilder();
- newSlot = requestPathMetricsCollector.aggregatePaths(3,
- queue -> !queue.isWriteOperation());
- requestPathMetricsCollector.logTopPaths(newSlot,
- entry -> sb2.append(entry.getKey() + " : " + entry.getValue() + "\n"));
- Assert.assertTrue(sb2.toString().startsWith("/path1/path2/path3 : 1110001"));
- StringBuilder sb3= new StringBuilder();
+ StringBuilder sb1 = new StringBuilder();
+ Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> queue.isWriteOperation());
+ requestPathMetricsCollector.logTopPaths(newSlot, entry -> sb1.append(entry.getKey()
+ + " : "
+ + entry.getValue()
+ + "\n"));
+ assertTrue(sb1.toString().startsWith("/path1/path2/path3 : 1000"));
+ StringBuilder sb2 = new StringBuilder();
+ newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> !queue.isWriteOperation());
+ requestPathMetricsCollector.logTopPaths(newSlot, entry -> sb2.append(entry.getKey()
+ + " : "
+ + entry.getValue()
+ + "\n"));
+ assertTrue(sb2.toString().startsWith("/path1/path2/path3 : 1110001"));
+ StringBuilder sb3 = new StringBuilder();
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> true);
- requestPathMetricsCollector.logTopPaths(newSlot,
- entry -> sb3.append(entry.getKey() + " : " + entry.getValue() + "\n"));
- Assert.assertTrue(sb3.toString().startsWith("/path1/path2/path3/path4 : 1110001"));
+ requestPathMetricsCollector.logTopPaths(newSlot, entry -> sb3.append(entry.getKey()
+ + " : "
+ + entry.getValue()
+ + "\n"));
+ assertTrue(sb3.toString().startsWith("/path1/path2/path3/path4 : 1110001"));
}
@Test
@@ -430,37 +418,34 @@ public class RequestPathMetricsCollectorTest {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector();
Random rand = new Random(System.currentTimeMillis());
Long startTime = System.currentTimeMillis();
- ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
//call 100k get Data
- for(int i = 0; i < 100000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(getData,
- "/path1/path2/path"+rand.nextInt(10))));
+ for (int i = 0; i < 100000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(getData, "/path1/path2/path"
+ + rand.nextInt(10))));
}
//5K create
- for(int i = 0; i < 5000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(create2,
- "/path1/path2/path"+rand.nextInt(10) )));
+ for (int i = 0; i < 5000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(create2, "/path1/path2/path"
+ + rand.nextInt(10))));
}
//5K delete
- for(int i = 0; i < 5000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(delete,
- "/path1/path2/path"+rand.nextInt(10) )));
+ for (int i = 0; i < 5000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(delete, "/path1/path2/path"
+ + rand.nextInt(10))));
}
//40K getChildren
- for(int i = 0; i < 40000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(getChildren,
- "/path1/path2/path"+rand.nextInt(10) )));
+ for (int i = 0; i < 40000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(getChildren, "/path1/path2/path"
+ + rand.nextInt(10))));
}
executor.shutdown();
//wait for at most 10 mill seconds
executor.awaitTermination(10, TimeUnit.MILLISECONDS);
- Assert.assertTrue(executor.isTerminated());
+ assertTrue(executor.isTerminated());
Long endTime = System.currentTimeMillis();
//less than 2 seconds total time
- Assert.assertTrue(TimeUnit.MILLISECONDS.toSeconds(endTime-startTime) < 3);
+ assertTrue(TimeUnit.MILLISECONDS.toSeconds(endTime - startTime) < 3);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java
index b2d563006..5caa71800 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,19 +18,6 @@
package org.apache.zookeeper.server.util;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.OutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.server.Request;
-import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -41,6 +28,17 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.jute.OutputArchive;
+import org.apache.jute.Record;
+import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.txn.TxnHeader;
+import org.junit.Test;
+import org.mockito.InOrder;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
public class SerializeUtilsTest {
@@ -125,4 +123,5 @@ public class SerializeUtilsTest {
baos.close();
assertArrayEquals(baos.toByteArray(), data);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java
index 0bf5b61db..925b01fea 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -18,10 +18,8 @@
package org.apache.zookeeper.server.util;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertEquals;
import java.io.File;
-
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
@@ -33,30 +31,27 @@ public class VerifyingFileFactoryTest extends ZKTestCase {
private Logger log;
@Before
- public void setUp(){
+ public void setUp() {
log = LoggerFactory.getLogger("TODO: Mock Logging");
}
@Test
public void testForWarningOnRelativePath() {
- VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log)
- .warnForRelativePath().build();
+ VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).warnForRelativePath().build();
vff.create("a/relative/path");
// assertTrue(log.hasWarned);
}
@Test
public void testForNoWarningOnIntendedRelativePath() {
- VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log)
- .warnForRelativePath().build();
+ VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).warnForRelativePath().build();
vff.create("./an/intended/relative/path");
// assertFalse(log.hasWarned);
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testForFailForNonExistingPath() {
- VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log)
- .failForNonExistingPath().build();
+ VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).failForNonExistingPath().build();
vff.create("/I/H0p3/this/path/d035/n0t/ex15t");
}
@@ -66,4 +61,5 @@ public class VerifyingFileFactoryTest extends ZKTestCase {
VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).build();
assertEquals(file, vff.create(file.getPath()));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java
index b106d073b..0ce0a59a0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java
@@ -14,39 +14,39 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
-import java.util.Arrays;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
-import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
-import org.apache.zookeeper.server.DumbWatcher;
-import org.apache.zookeeper.server.ServerCnxn;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.server.DumbWatcher;
+import org.apache.zookeeper.server.ServerCnxn;
import org.apache.zookeeper.server.ServerMetrics;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public class WatchManagerTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(WatchManagerTest.class);
private static final String PATH_PREFIX = "path";
@@ -60,11 +60,8 @@ public class WatchManagerTest extends ZKTestCase {
}
@Parameterized.Parameters
- public static List<Object []> data() {
- return Arrays.asList(new Object [][] {
- {WatchManager.class.getName()},
- {WatchManagerOptimized.class.getName()}
- });
+ public static List<Object[]> data() {
+ return Arrays.asList(new Object[][]{{WatchManager.class.getName()}, {WatchManagerOptimized.class.getName()}});
}
@Before
@@ -95,8 +92,8 @@ public class WatchManagerTest extends ZKTestCase {
private final AtomicInteger watchesAdded;
private volatile boolean stopped = false;
- public AddWatcherWorker(IWatchManager manager,
- int paths, int watchers, AtomicInteger watchesAdded) {
+ public AddWatcherWorker(
+ IWatchManager manager, int paths, int watchers, AtomicInteger watchesAdded) {
this.manager = manager;
this.paths = paths;
this.watchers = watchers;
@@ -117,6 +114,7 @@ public class WatchManagerTest extends ZKTestCase {
public void shutdown() {
stopped = true;
}
+
}
public class WatcherTriggerWorker extends Thread {
@@ -126,8 +124,8 @@ public class WatchManagerTest extends ZKTestCase {
private final AtomicInteger triggeredCount;
private volatile boolean stopped = false;
- public WatcherTriggerWorker(IWatchManager manager,
- int paths, AtomicInteger triggeredCount) {
+ public WatcherTriggerWorker(
+ IWatchManager manager, int paths, AtomicInteger triggeredCount) {
this.manager = manager;
this.paths = paths;
this.triggeredCount = triggeredCount;
@@ -137,20 +135,21 @@ public class WatchManagerTest extends ZKTestCase {
public void run() {
while (!stopped) {
String path = PATH_PREFIX + r.nextInt(paths);
- WatcherOrBitSet s = manager.triggerWatch(
- path, EventType.NodeDeleted);
+ WatcherOrBitSet s = manager.triggerWatch(path, EventType.NodeDeleted);
if (s != null) {
triggeredCount.addAndGet(s.size());
}
try {
Thread.sleep(r.nextInt(10));
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
}
public void shutdown() {
stopped = true;
}
+
}
public class RemoveWatcherWorker extends Thread {
@@ -161,8 +160,8 @@ public class WatchManagerTest extends ZKTestCase {
private final AtomicInteger watchesRemoved;
private volatile boolean stopped = false;
- public RemoveWatcherWorker(IWatchManager manager,
- int paths, int watchers, AtomicInteger watchesRemoved) {
+ public RemoveWatcherWorker(
+ IWatchManager manager, int paths, int watchers, AtomicInteger watchesRemoved) {
this.manager = manager;
this.paths = paths;
this.watchers = watchers;
@@ -179,7 +178,8 @@ public class WatchManagerTest extends ZKTestCase {
}
try {
Thread.sleep(r.nextInt(10));
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
}
@@ -196,8 +196,8 @@ public class WatchManagerTest extends ZKTestCase {
private final Set<Watcher> removedWatchers;
private volatile boolean stopped = false;
- public CreateDeadWatchersWorker(IWatchManager manager,
- int watchers, Set<Watcher> removedWatchers) {
+ public CreateDeadWatchersWorker(
+ IWatchManager manager, int watchers, Set<Watcher> removedWatchers) {
this.manager = manager;
this.watchers = watchers;
this.removedWatchers = removedWatchers;
@@ -214,7 +214,8 @@ public class WatchManagerTest extends ZKTestCase {
}
try {
Thread.sleep(r.nextInt(10));
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
}
@@ -237,11 +238,9 @@ public class WatchManagerTest extends ZKTestCase {
// 1. start 5 workers to trigger watchers on that path
// count all the watchers have been fired
AtomicInteger watchTriggered = new AtomicInteger();
- List<WatcherTriggerWorker> triggerWorkers =
- new ArrayList<WatcherTriggerWorker>();
+ List<WatcherTriggerWorker> triggerWorkers = new ArrayList<WatcherTriggerWorker>();
for (int i = 0; i < 5; i++) {
- WatcherTriggerWorker worker =
- new WatcherTriggerWorker(manager, paths, watchTriggered);
+ WatcherTriggerWorker worker = new WatcherTriggerWorker(manager, paths, watchTriggered);
triggerWorkers.add(worker);
worker.start();
}
@@ -251,8 +250,7 @@ public class WatchManagerTest extends ZKTestCase {
AtomicInteger watchesAdded = new AtomicInteger();
List<AddWatcherWorker> addWorkers = new ArrayList<AddWatcherWorker>();
for (int i = 0; i < 5; i++) {
- AddWatcherWorker worker = new AddWatcherWorker(
- manager, paths, watchers, watchesAdded);
+ AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded);
addWorkers.add(worker);
worker.start();
}
@@ -260,11 +258,12 @@ public class WatchManagerTest extends ZKTestCase {
while (watchesAdded.get() < 100000) {
try {
Thread.sleep(100);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
// 3. stop all the addWorkers
- for (AddWatcherWorker worker: addWorkers) {
+ for (AddWatcherWorker worker : addWorkers) {
worker.shutdown();
}
@@ -272,16 +271,17 @@ public class WatchManagerTest extends ZKTestCase {
// all watchers added are fired
try {
Thread.sleep(500);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
// 5. stop all triggerWorkers
- for (WatcherTriggerWorker worker: triggerWorkers) {
+ for (WatcherTriggerWorker worker : triggerWorkers) {
worker.shutdown();
}
// 6. make sure the total watch triggered is same as added
- Assert.assertTrue(watchesAdded.get() > 0);
- Assert.assertEquals(watchesAdded.get(), watchTriggered.get());
+ assertTrue(watchesAdded.get() > 0);
+ assertEquals(watchesAdded.get(), watchTriggered.get());
}
/**
@@ -297,11 +297,9 @@ public class WatchManagerTest extends ZKTestCase {
// 1. start 5 workers to remove watchers on those path
// record the watchers have been removed
AtomicInteger watchesRemoved = new AtomicInteger();
- List<RemoveWatcherWorker> removeWorkers =
- new ArrayList<RemoveWatcherWorker>();
+ List<RemoveWatcherWorker> removeWorkers = new ArrayList<RemoveWatcherWorker>();
for (int i = 0; i < 5; i++) {
- RemoveWatcherWorker worker =
- new RemoveWatcherWorker(manager, paths, watchers, watchesRemoved);
+ RemoveWatcherWorker worker = new RemoveWatcherWorker(manager, paths, watchers, watchesRemoved);
removeWorkers.add(worker);
worker.start();
}
@@ -311,8 +309,7 @@ public class WatchManagerTest extends ZKTestCase {
AtomicInteger watchesAdded = new AtomicInteger();
List<AddWatcherWorker> addWorkers = new ArrayList<AddWatcherWorker>();
for (int i = 0; i < 5; i++) {
- AddWatcherWorker worker = new AddWatcherWorker(
- manager, paths, watchers, watchesAdded);
+ AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded);
addWorkers.add(worker);
worker.start();
}
@@ -320,28 +317,29 @@ public class WatchManagerTest extends ZKTestCase {
while (watchesAdded.get() < 100000) {
try {
Thread.sleep(100);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
// 3. stop all workers
- for (RemoveWatcherWorker worker: removeWorkers) {
+ for (RemoveWatcherWorker worker : removeWorkers) {
worker.shutdown();
}
- for (AddWatcherWorker worker: addWorkers) {
+ for (AddWatcherWorker worker : addWorkers) {
worker.shutdown();
}
// 4. sleep for a while to make sure all the thread exited
try {
Thread.sleep(500);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
// 5. make sure left watches + removed watches = added watches
- Assert.assertTrue(watchesAdded.get() > 0);
- Assert.assertTrue(watchesRemoved.get() > 0);
- Assert.assertTrue(manager.size() > 0);
- Assert.assertEquals(
- watchesAdded.get(), watchesRemoved.get() + manager.size());
+ assertTrue(watchesAdded.get() > 0);
+ assertTrue(watchesRemoved.get() > 0);
+ assertTrue(manager.size() > 0);
+ assertEquals(watchesAdded.get(), watchesRemoved.get() + manager.size());
}
/**
@@ -360,11 +358,9 @@ public class WatchManagerTest extends ZKTestCase {
// 1. start 5 workers to randomly mark those watcher as dead
// and remove them from watch manager
Set<Watcher> deadWatchers = new HashSet<Watcher>();
- List<CreateDeadWatchersWorker> deadWorkers =
- new ArrayList<CreateDeadWatchersWorker>();
+ List<CreateDeadWatchersWorker> deadWorkers = new ArrayList<CreateDeadWatchersWorker>();
for (int i = 0; i < 5; i++) {
- CreateDeadWatchersWorker worker = new CreateDeadWatchersWorker(
- manager, watchers, deadWatchers);
+ CreateDeadWatchersWorker worker = new CreateDeadWatchersWorker(manager, watchers, deadWatchers);
deadWorkers.add(worker);
worker.start();
}
@@ -373,8 +369,7 @@ public class WatchManagerTest extends ZKTestCase {
AtomicInteger watchesAdded = new AtomicInteger();
List<AddWatcherWorker> addWorkers = new ArrayList<AddWatcherWorker>();
for (int i = 0; i < 5; i++) {
- AddWatcherWorker worker = new AddWatcherWorker(
- manager, paths, watchers, watchesAdded);
+ AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded);
addWorkers.add(worker);
worker.start();
}
@@ -382,14 +377,15 @@ public class WatchManagerTest extends ZKTestCase {
while (watchesAdded.get() < 50000) {
try {
Thread.sleep(100);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
// 3. stop all workers
- for (CreateDeadWatchersWorker worker: deadWorkers) {
+ for (CreateDeadWatchersWorker worker : deadWorkers) {
worker.shutdown();
}
- for (AddWatcherWorker worker: addWorkers) {
+ for (AddWatcherWorker worker : addWorkers) {
worker.shutdown();
}
@@ -398,24 +394,24 @@ public class WatchManagerTest extends ZKTestCase {
// So need to sleep as least that long
try {
Thread.sleep(2000);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
// 5. make sure the dead watchers are not in the existing watchers
WatchesReport existingWatchers = manager.getWatches();
- for (Watcher w: deadWatchers) {
- Assert.assertFalse(
- existingWatchers.hasPaths(((ServerCnxn) w).getSessionId()));
+ for (Watcher w : deadWatchers) {
+ assertFalse(existingWatchers.hasPaths(((ServerCnxn) w).getSessionId()));
}
}
- private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum){
+ private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum) {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(min, values.get("min_" + metricName));
- Assert.assertEquals(max, values.get("max_" + metricName));
- Assert.assertEquals(avg, (Double)values.get("avg_" + metricName), 0.000001);
- Assert.assertEquals(cnt, values.get("cnt_" + metricName));
- Assert.assertEquals(sum, values.get("sum_" + metricName));
+ assertEquals(min, values.get("min_" + metricName));
+ assertEquals(max, values.get("max_" + metricName));
+ assertEquals(avg, (Double) values.get("avg_" + metricName), 0.000001);
+ assertEquals(cnt, values.get("cnt_" + metricName));
+ assertEquals(sum, values.get("sum_" + metricName));
}
@Test
@@ -470,4 +466,5 @@ public class WatchManagerTest extends ZKTestCase {
//make sure that node created watch count is not impacted by the fire of other event types
checkMetrics("node_created_watch_count", 1L, 2L, 1.5D, 2L, 3L);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java
index cf0a5f435..5152b5eb2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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.
@@ -14,28 +14,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
-import java.util.HashMap;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.metrics.impl.DefaultMetricsProvider;
import org.apache.zookeeper.server.ServerMetrics;
import org.junit.Test;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-
public class WatcherCleanerTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(WatcherCleanerTest.class);
public static class MyDeadWatcherListener implements IDeadWatcherListener {
@@ -57,7 +58,8 @@ public class WatcherCleanerTest extends ZKTestCase {
if (delayMs > 0) {
try {
Thread.sleep(delayMs);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
this.deadWatchers.clear();
this.deadWatchers.addAll(deadWatchers);
@@ -71,9 +73,11 @@ public class WatcherCleanerTest extends ZKTestCase {
public boolean wait(int maxWaitMs) {
try {
return latch.await(maxWaitMs, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
return false;
}
+
}
@Test
@@ -88,13 +92,13 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(i);
}
// not trigger processDeadWatchers yet
- Assert.assertEquals(0, listener.getDeadWatchers().size());
+ assertEquals(0, listener.getDeadWatchers().size());
listener.setCountDownLatch(new CountDownLatch(1));
// add another dead watcher to trigger the process
cleaner.addDeadWatcher(i);
- Assert.assertTrue(listener.wait(1000));
- Assert.assertEquals(threshold, listener.getDeadWatchers().size());
+ assertTrue(listener.wait(1000));
+ assertEquals(threshold, listener.getDeadWatchers().size());
}
@Test
@@ -105,15 +109,15 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(1);
// not trigger processDeadWatchers yet
- Assert.assertEquals(0, listener.getDeadWatchers().size());
+ assertEquals(0, listener.getDeadWatchers().size());
listener.setCountDownLatch(new CountDownLatch(1));
- Assert.assertTrue(listener.wait(2000));
- Assert.assertEquals(1, listener.getDeadWatchers().size());
+ assertTrue(listener.wait(2000));
+ assertEquals(1, listener.getDeadWatchers().size());
// won't trigger event if there is no dead watchers
listener.setCountDownLatch(new CountDownLatch(1));
- Assert.assertFalse(listener.wait(2000));
+ assertFalse(listener.wait(2000));
}
@Test
@@ -131,8 +135,8 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(2);
long time = Time.currentElapsedTime() - startTime;
System.out.println("time used " + time);
- Assert.assertTrue(Time.currentElapsedTime() - startTime >= delayMs);
- Assert.assertTrue(listener.wait(5000));
+ assertTrue(Time.currentElapsedTime() - startTime >= delayMs);
+ assertTrue(listener.wait(5000));
}
@Test
@@ -149,23 +153,22 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(2);
cleaner.addDeadWatcher(3);
- Assert.assertTrue(listener.wait(5000));
-
+ assertTrue(listener.wait(5000));
+
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertThat("Adding dead watcher should be stalled twice",
- (Long)values.get("add_dead_watcher_stall_time"),
- greaterThan(0L));
- Assert.assertEquals("Total dead watchers added to the queue should be 3", 3L, values.get("dead_watchers_queued"));
- Assert.assertEquals("Total dead watchers cleared should be 3", 3L, values.get("dead_watchers_cleared"));
+ assertThat("Adding dead watcher should be stalled twice", (Long) values.get("add_dead_watcher_stall_time"), greaterThan(0L));
+ assertEquals("Total dead watchers added to the queue should be 3", 3L, values.get("dead_watchers_queued"));
+ assertEquals("Total dead watchers cleared should be 3", 3L, values.get("dead_watchers_cleared"));
- Assert.assertEquals(3L, values.get("cnt_dead_watchers_cleaner_latency"));
+ assertEquals(3L, values.get("cnt_dead_watchers_cleaner_latency"));
//Each latency should be a little over 20 ms, allow 5 ms deviation
- Assert.assertEquals(20D, (Double)values.get("avg_dead_watchers_cleaner_latency"), 5);
- Assert.assertEquals(20D, ((Long)values.get("min_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("max_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("p50_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("p95_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("p99_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, (Double) values.get("avg_dead_watchers_cleaner_latency"), 5);
+ assertEquals(20D, ((Long) values.get("min_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("max_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("p50_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("p95_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("p99_dead_watchers_cleaner_latency")).doubleValue(), 5);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java
index 03334a33b..ee105dfa6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java
@@ -14,18 +14,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
-import java.util.Set;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.HashSet;
-
+import java.util.Set;
import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.DumbWatcher;
import org.apache.zookeeper.server.util.BitHashSet;
-
-import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class WatcherOrBitSetTest extends ZKTestCase {
@@ -33,29 +34,30 @@ public class WatcherOrBitSetTest extends ZKTestCase {
public void testWatcherSet() {
Set<Watcher> wset = new HashSet<Watcher>();
WatcherOrBitSet hashSet = new WatcherOrBitSet(wset);
- Assert.assertEquals(0, hashSet.size());
+ assertEquals(0, hashSet.size());
DumbWatcher w1 = new DumbWatcher();
- Assert.assertFalse(hashSet.contains(w1));
+ assertFalse(hashSet.contains(w1));
wset.add(w1);
- Assert.assertTrue(hashSet.contains(w1));
- Assert.assertEquals(1, hashSet.size());
- Assert.assertFalse(hashSet.contains(1));
+ assertTrue(hashSet.contains(w1));
+ assertEquals(1, hashSet.size());
+ assertFalse(hashSet.contains(1));
}
@Test
public void testBitSet() {
BitHashSet bset = new BitHashSet(0);
WatcherOrBitSet bitSet = new WatcherOrBitSet(bset);
- Assert.assertEquals(0, bitSet.size());
+ assertEquals(0, bitSet.size());
Integer bit = 1;
- Assert.assertFalse(bitSet.contains(1));
- Assert.assertFalse(bitSet.contains(bit));
+ assertFalse(bitSet.contains(1));
+ assertFalse(bitSet.contains(bit));
bset.add(bit);
- Assert.assertTrue(bitSet.contains(1));
- Assert.assertTrue(bitSet.contains(bit));
- Assert.assertEquals(1, bitSet.size());
+ assertTrue(bitSet.contains(1));
+ assertTrue(bitSet.contains(bit));
+ assertEquals(1, bitSet.size());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java
index 34e378952..123b49bd5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java
@@ -14,8 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -23,12 +28,13 @@ import java.util.Set;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class WatchesPathReportTest extends ZKTestCase {
+
private Map<String, Set<Long>> m;
private WatchesPathReport r;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
m = new HashMap<String, Set<Long>>();
Set<Long> s = new HashSet<Long>();
s.add(101L);
@@ -39,12 +45,14 @@ public class WatchesPathReportTest extends ZKTestCase {
m.put("path2", s);
r = new WatchesPathReport(m);
}
- @Test public void testHasSessions() {
+ @Test
+ public void testHasSessions() {
assertTrue(r.hasSessions("path1"));
assertTrue(r.hasSessions("path2"));
assertFalse(r.hasSessions("path3"));
}
- @Test public void testGetSessions() {
+ @Test
+ public void testGetSessions() {
Set<Long> s = r.getSessions("path1");
assertEquals(2, s.size());
assertTrue(s.contains(101L));
@@ -54,7 +62,9 @@ public class WatchesPathReportTest extends ZKTestCase {
assertTrue(s.contains(201L));
assertNull(r.getSessions("path3"));
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
assertEquals(m, r.toMap());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java
index 237583a46..05c0547d9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java
@@ -14,8 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -23,12 +28,13 @@ import java.util.Set;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class WatchesReportTest extends ZKTestCase {
+
private Map<Long, Set<String>> m;
private WatchesReport r;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
m = new HashMap<Long, Set<String>>();
Set<String> s = new HashSet<String>();
s.add("path1a");
@@ -39,12 +45,14 @@ public class WatchesReportTest extends ZKTestCase {
m.put(2L, s);
r = new WatchesReport(m);
}
- @Test public void testHasPaths() {
+ @Test
+ public void testHasPaths() {
assertTrue(r.hasPaths(1L));
assertTrue(r.hasPaths(2L));
assertFalse(r.hasPaths(3L));
}
- @Test public void testGetPaths() {
+ @Test
+ public void testGetPaths() {
Set<String> s = r.getPaths(1L);
assertEquals(2, s.size());
assertTrue(s.contains("path1a"));
@@ -54,7 +62,9 @@ public class WatchesReportTest extends ZKTestCase {
assertTrue(s.contains("path2a"));
assertNull(r.getPaths(3L));
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
assertEquals(m, r.toMap());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java
index 35956f185..9d53281ed 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java
@@ -14,29 +14,35 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class WatchesSummaryTest extends ZKTestCase {
+
private WatchesSummary s;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
s = new WatchesSummary(1, 2, 3);
}
- @Test public void testGetters() {
+ @Test
+ public void testGetters() {
assertEquals(1, s.getNumConnections());
assertEquals(2, s.getNumPaths());
assertEquals(3, s.getTotalWatches());
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
Map<String, Object> m = s.toMap();
assertEquals(3, m.size());
assertEquals(Integer.valueOf(1), m.get(WatchesSummary.KEY_NUM_CONNECTIONS));
assertEquals(Integer.valueOf(2), m.get(WatchesSummary.KEY_NUM_PATHS));
assertEquals(Integer.valueOf(3), m.get(WatchesSummary.KEY_NUM_TOTAL_WATCHES));
}
+
}