You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@zookeeper.apache.org by an...@apache.org on 2018/10/05 13:36:39 UTC
[11/51] [partial] zookeeper git commit: ZOOKEEPER-3032: MAVEN
MIGRATION - branch-3.5 - move java server, client
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/WatchesSummaryTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/WatchesSummaryTest.java b/src/java/test/org/apache/zookeeper/server/WatchesSummaryTest.java
deleted file mode 100644
index d679065..0000000
--- a/src/java/test/org/apache/zookeeper/server/WatchesSummaryTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper.server;
-
-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() {
- s = new WatchesSummary(1, 2, 3);
- }
- @Test public void testGetters() {
- assertEquals(1, s.getNumConnections());
- assertEquals(2, s.getNumPaths());
- assertEquals(3, s.getTotalWatches());
- }
- @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));
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
deleted file mode 100644
index 08adfdc..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper.server;
-
-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;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.txn.SetDataTxn;
-import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.After;
-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");
- }
-
- @After
- public void teardown() throws Exception {
- System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
- }
-
- @Test
- public void testTxnLogElapsedSyncTime() throws IOException {
-
- File tmpDir = ClientBase.createTmpDir();
- FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"),
- new File(tmpDir, "data_txnlog"));
-
- ZooKeeperServer zks = new ZooKeeperServer();
- zks.setTxnLogFactory(fileTxnSnapLog);
-
- ZooKeeperServerBean serverBean = new ZooKeeperServerBean(zks);
- long elapsedTime = serverBean.getTxnLogElapsedSyncTime();
- assertEquals(-1, elapsedTime);
-
- TxnHeader hdr = new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.setData);
- Record txn = new SetDataTxn("/foo", new byte[0], 1);
- Request req = new Request(0, 0, 0, hdr, txn, 0);
-
- try {
-
- zks.getTxnLogFactory().append(req);
- zks.getTxnLogFactory().commit();
- elapsedTime = serverBean.getTxnLogElapsedSyncTime();
-
- assertNotEquals(-1, elapsedTime);
-
- assertEquals(elapsedTime, serverBean.getTxnLogElapsedSyncTime());
-
- } finally {
- fileTxnSnapLog.close();
- }
- }
-
- @Test
- public void testGetSecureClientPort() throws IOException {
- ZooKeeperServer zks = new ZooKeeperServer();
- /**
- * case 1: When secure client is not configured GetSecureClientPort
- * should return empty string
- */
- ZooKeeperServerBean serverBean = new ZooKeeperServerBean(zks);
- String result = serverBean.getSecureClientPort();
- assertEquals("", result);
-
- /**
- * case 2: When secure client is configured GetSecureClientPort should
- * return configured port
- */
-
- ServerCnxnFactory cnxnFactory = ServerCnxnFactory.createFactory();
- int secureClientPort = 8443;
- InetSocketAddress address = new InetSocketAddress(secureClientPort);
- cnxnFactory.configure(address, 5, true);
- zks.setSecureServerCnxnFactory(cnxnFactory);
-
- result = serverBean.getSecureClientPort();
- assertEquals(Integer.toString(secureClientPort), result);
-
- // cleanup
- cnxnFactory.shutdown();
-
- }
-
- @Test
- public void testGetSecureClientAddress() throws IOException {
- ZooKeeperServer zks = new ZooKeeperServer();
- /**
- * case 1: When secure client is not configured getSecureClientAddress
- * should return empty string
- */
- ZooKeeperServerBean serverBean = new ZooKeeperServerBean(zks);
- String result = serverBean.getSecureClientPort();
- assertEquals("", result);
-
- /**
- * case 2: When secure client is configured getSecureClientAddress
- * should return configured SecureClientAddress
- */
-
- ServerCnxnFactory cnxnFactory = ServerCnxnFactory.createFactory();
- int secureClientPort = 8443;
- InetSocketAddress address = new InetSocketAddress(secureClientPort);
- cnxnFactory.configure(address, 5, true);
- zks.setSecureServerCnxnFactory(cnxnFactory);
-
- result = serverBean.getSecureClientAddress();
- String ipv4 = "0.0.0.0:" + secureClientPort;
- String ipv6 = "0:0:0:0:0:0:0:0:" + secureClientPort;
- assertTrue(result.equals(ipv4) || result.equals(ipv6));
-
- // cleanup
- cnxnFactory.shutdown();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerConfTest.java b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
deleted file mode 100644
index b53321a..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper.server;
-
-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() {
- c = new ZooKeeperServerConf(1, "a", "b", 2, 3, 4, 5, 6L);
- }
- @Test public void testGetters() {
- assertEquals(1, c.getClientPort());
- assertEquals("a", c.getDataDir());
- assertEquals("b", c.getDataLogDir());
- assertEquals(2, c.getTickTime());
- assertEquals(3, c.getMaxClientCnxnsPerHost());
- assertEquals(4, c.getMinSessionTimeout());
- assertEquals(5, c.getMaxSessionTimeout());
- assertEquals(6L, c.getServerId());
- }
- @Test public void testToMap() {
- Map<String, Object> m = c.toMap();
- assertEquals(8, m.size());
- assertEquals(Integer.valueOf(1), m.get(ZooKeeperServerConf.KEY_CLIENT_PORT));
- assertEquals("a", m.get(ZooKeeperServerConf.KEY_DATA_DIR));
- assertEquals("b", m.get(ZooKeeperServerConf.KEY_DATA_LOG_DIR));
- assertEquals(Integer.valueOf(2), m.get(ZooKeeperServerConf.KEY_TICK_TIME));
- assertEquals(Integer.valueOf(3), m.get(ZooKeeperServerConf.KEY_MAX_CLIENT_CNXNS));
- assertEquals(Integer.valueOf(4), m.get(ZooKeeperServerConf.KEY_MIN_SESSION_TIMEOUT));
- assertEquals(Integer.valueOf(5), m.get(ZooKeeperServerConf.KEY_MAX_SESSION_TIMEOUT));
- assertEquals(Long.valueOf(6L), m.get(ZooKeeperServerConf.KEY_SERVER_ID));
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerMainTest.java b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
deleted file mode 100644
index 01b6560..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
+++ /dev/null
@@ -1,567 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-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.ZooDefs.Ids;
-import org.apache.zookeeper.common.PathUtils;
-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;
-
-/**
- * Test stand-alone server.
- *
- */
-public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
- 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 {
- this(clientPort, preCreateDirs, ClientBase.createTmpDir(), configs);
- }
-
- 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");
-
- FileWriter fwriter = new FileWriter(confFile);
- fwriter.write("tickTime=2000\n");
- fwriter.write("initLimit=10\n");
- fwriter.write("syncLimit=5\n");
- if(configs != null){
- fwriter.write(configs);
- }
-
- dataDir = new File(this.tmpDir, "data");
- logDir = new File(dataDir.toString() + "_txnlog");
- if (preCreateDirs) {
- if (!dataDir.mkdir()) {
- throw new IOException("unable to mkdir " + dataDir);
- }
- if (!logDir.mkdir()) {
- throw new IOException("unable to mkdir " + logDir);
- }
- }
-
- String normalizedDataDir = PathUtils.normalizeFileSystemPath(dataDir.toString());
- String normalizedLogDir = PathUtils.normalizeFileSystemPath(logDir.toString());
- fwriter.write("dataDir=" + normalizedDataDir + "\n");
- fwriter.write("dataLogDir=" + normalizedLogDir + "\n");
- fwriter.write("clientPort=" + clientPort + "\n");
- fwriter.flush();
- fwriter.close();
-
- main = new TestZKSMain();
- }
-
- public void run() {
- String args[] = new String[1];
- args[0] = confFile.toString();
- try {
- main.initializeAndRun(args);
- } catch (Exception e) {
- // test will still fail even though we just log/ignore
- LOG.error("unexpected exception in run", e);
- }
- }
-
- public void shutdown() throws IOException {
- main.shutdown();
- }
-
- void deleteDirs() throws IOException{
- delete(tmpDir);
- }
-
- void delete(File f) throws IOException {
- if (f.isDirectory()) {
- for (File c : f.listFiles())
- delete(c);
- }
- 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 void shutdown() {
- super.shutdown();
- }
- }
-
- /**
- * Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2247.
- * Test to verify that even after non recoverable error (error while
- * writing transaction log), ZooKeeper is still available.
- */
- @Test(timeout = 30000)
- public void testNonRecoverableError() throws Exception {
- ClientBase.setupTestEnv();
-
- final int CLIENT_PORT = PortAssignment.unique();
-
- 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));
-
-
- 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");
-
- // inject problem in server
- ZooKeeperServer zooKeeperServer = main.getCnxnFactory()
- .getZooKeeperServer();
- FileTxnSnapLog snapLog = zooKeeperServer.getTxnLogFactory();
- FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(
- snapLog.getDataDir(), snapLog.getSnapDir()) {
- @Override
- public void commit() throws IOException {
- throw new IOException("Input/output error");
- }
- };
- ZKDatabase newDB = new ZKDatabase(fileTxnSnapLogWithError);
- zooKeeperServer.setZKDatabase(newDB);
-
- try {
- // do create operation, so that injected IOException is thrown
- 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));
- fileTxnSnapLogWithError.close();
- main.shutdown();
- main.deleteDirs();
- }
-
- /**
- * Tests that the ZooKeeper server will fail to start if the
- * snapshot directory is read only.
- *
- * This test will fail if it is executed as root user.
- */
- @Test(timeout = 30000)
- public void testReadOnlySnapshotDir() throws Exception {
- ClientBase.setupTestEnv();
- final int CLIENT_PORT = PortAssignment.unique();
-
- // Start up the ZK server to automatically create the necessary directories
- // and capture the directory where data is stored
- 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));
- main.shutdown();
-
- // Make the snapshot directory read only
- File snapDir = new File(main.dataDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
- snapDir.setWritable(false);
-
- // Restart ZK and observe a failure
- 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));
-
- main.shutdown();
-
- snapDir.setWritable(true);
-
- main.deleteDirs();
- }
-
- /**
- * Tests that the ZooKeeper server will fail to start if the
- * transaction log directory is read only.
- *
- * This test will fail if it is executed as root user.
- */
- @Test(timeout = 30000)
- public void testReadOnlyTxnLogDir() throws Exception {
- ClientBase.setupTestEnv();
- final int CLIENT_PORT = PortAssignment.unique();
-
- // Start up the ZK server to automatically create the necessary directories
- // and capture the directory where data is stored
- 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));
- main.shutdown();
-
- // Make the transaction log directory read only
- File logDir = new File(main.logDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
- logDir.setWritable(false);
-
- // Restart ZK and observe a failure
- 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));
-
- main.shutdown();
-
- logDir.setWritable(true);
-
- main.deleteDirs();
- }
-
- /**
- * Verify the ability to start a standalone server instance.
- */
- @Test
- public void testStandalone() throws Exception {
- ClientBase.setupTestEnv();
-
- final int CLIENT_PORT = PortAssignment.unique();
-
- 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));
-
- 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");
- 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));
- }
-
- /**
- * Test verifies server should fail when data dir or data log dir doesn't
- * exists. Sets "zookeeper.datadir.autocreate" to false.
- */
- @Test(timeout = 30000)
- public void testWithoutAutoCreateDataLogDir() throws Exception {
- ClientBase.setupTestEnv();
- System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE, "false");
- try {
- final int CLIENT_PORT = PortAssignment.unique();
-
- MainThread main = new MainThread(CLIENT_PORT, false, null);
- String args[] = new String[1];
- args[0] = main.confFile.toString();
- main.start();
-
- Assert.assertFalse("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
- } finally {
- // resets "zookeeper.datadir.autocreate" flag
- System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE,
- FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE_DEFAULT);
- }
- }
-
- /**
- * Test verifies the auto creation of data dir and data log dir.
- * Sets "zookeeper.datadir.autocreate" to true.
- */
- @Test(timeout = 30000)
- public void testWithAutoCreateDataLogDir() throws Exception {
- ClientBase.setupTestEnv();
- System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE, "true");
- final int CLIENT_PORT = PortAssignment.unique();
-
- MainThread main = new MainThread(CLIENT_PORT, false, null);
- String args[] = new String[1];
- args[0] = main.confFile.toString();
- main.start();
-
- Assert.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");
- 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));
- }
-
- /**
- * Test verifies that the server shouldn't allow minsessiontimeout >
- * maxsessiontimeout
- */
- @Test
- 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";
- MainThread main = new MainThread(CLIENT_PORT, false, configs);
- String args[] = new String[1];
- args[0] = main.confFile.toString();
- try {
- main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as "
- + "minsessiontimeout > maxsessiontimeout");
- } catch (ConfigException iae) {
- // expected
- }
- }
-
- /**
- * Test verifies that the server is able to redefine if user configured only
- * minSessionTimeout limit
- */
- @Test
- public void testWithOnlyMinSessionTimeout() throws Exception {
- ClientBase.setupTestEnv();
-
- final int CLIENT_PORT = PortAssignment.unique();
- final int tickTime = 2000;
- final int minSessionTimeout = tickTime * 2 - 100;
- int maxSessionTimeout = 20 * tickTime;
- final String configs = "minSessionTimeout=" + minSessionTimeout + "\n";
- MainThread main = new MainThread(CLIENT_PORT, false, configs);
- main.start();
-
- String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
- Assert.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);
- // create session with max value
- verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
- verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout,
- HOSTPORT);
- main.shutdown();
- Assert.assertTrue("waiting for server down", ClientBase
- .waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
- }
-
- /**
- * Test verifies that the server is able to redefine the min/max session
- * timeouts
- */
- @Test
- public void testMinMaxSessionTimeOut() throws Exception {
- ClientBase.setupTestEnv();
-
- final int CLIENT_PORT = PortAssignment.unique();
- 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";
- MainThread main = new MainThread(CLIENT_PORT, false, configs);
- main.start();
-
- String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
- Assert.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);
- // create session with max value
- verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
- verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout,
- HOSTPORT);
- main.shutdown();
-
- Assert.assertTrue("waiting for server down", ClientBase
- .waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
- }
-
- 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());
- zk.close();
- }
-
- @Test
- public void testJMXRegistrationWithNIO() throws Exception {
- ClientBase.setupTestEnv();
- File tmpDir_1 = ClientBase.createTmpDir();
- ServerCnxnFactory server_1 = startServer(tmpDir_1);
- File tmpDir_2 = ClientBase.createTmpDir();
- ServerCnxnFactory server_2 = startServer(tmpDir_2);
-
- server_1.shutdown();
- server_2.shutdown();
-
- deleteFile(tmpDir_1);
- deleteFile(tmpDir_2);
- }
-
- @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());
- try {
- ClientBase.setupTestEnv();
- File tmpDir_1 = ClientBase.createTmpDir();
- ServerCnxnFactory server_1 = startServer(tmpDir_1);
- File tmpDir_2 = ClientBase.createTmpDir();
- ServerCnxnFactory server_2 = startServer(tmpDir_2);
-
- server_1.shutdown();
- server_2.shutdown();
-
- deleteFile(tmpDir_1);
- deleteFile(tmpDir_2);
- } finally {
- // setting back
- if (originalServerCnxnFactory == null
- || originalServerCnxnFactory.isEmpty()) {
- System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
- } else {
- System.setProperty(
- ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- originalServerCnxnFactory);
- }
- }
- }
-
- private void deleteFile(File f) throws IOException {
- if (f.isDirectory()) {
- for (File c : f.listFiles())
- deleteFile(c);
- }
- 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 {
- 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));
- return f;
- }
-
- public void process(WatchedEvent event) {
- if (event.getState() == KeeperState.SyncConnected) {
- clientConnected.countDown();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
deleted file mode 100644
index c78a9a0..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper.server;
-
-import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
-import static org.apache.zookeeper.server.command.AbstractFourLetterCommand.ZK_NOT_SERVING;
-
-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;
-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;
-
-/**
- * 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 int PORT = PortAssignment.unique();
- private static String HOST = "127.0.0.1";
- private static String HOSTPORT = HOST + ":" + PORT;
-
- private ServerCnxnFactory servcnxnf;
- private ZooKeeperServer zks;
- private File tmpDir;
- private CountDownLatch startupDelayLatch = new CountDownLatch(1);
-
- @After
- public void teardown() throws Exception {
- // count down to avoid infinite blocking call due to this latch, if
- // any.
- startupDelayLatch.countDown();
-
- if (servcnxnf != null) {
- servcnxnf.shutdown();
- }
- if (zks != null) {
- zks.shutdown();
- }
- if (zks.getZKDatabase() != null) {
- zks.getZKDatabase().close();
- }
- ClientBase.recursiveDelete(tmpDir);
- }
-
- /**
- * Test case for
- * {@link https://issues.apache.org/jira/browse/ZOOKEEPER-2383}.
- */
- @Test(timeout = 30000)
- 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));
-
- CountdownWatcher watcher = new CountdownWatcher();
- 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));
-
- 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));
-
- Assert.assertTrue(
- "Failed to invoke zks#createSession() method during client session creation",
- simplezks.waitForSessionCreation(5));
- watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zkClient.close();
- }
-
- /**
- * Test case for
- * {@link https://issues.apache.org/jira/browse/ZOOKEEPER-2383}.
- */
- @Test(timeout = 30000)
- public void testClientConnectionRequestDuringStartupWithNettyServerCnxn()
- throws Exception {
- tmpDir = ClientBase.createTmpDir();
- ClientBase.setupTestEnv();
-
- String originalServerCnxnFactory = System
- .getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
- try {
- 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));
-
- CountdownWatcher watcher = new CountdownWatcher();
- 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));
-
- 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));
-
- Assert.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);
- return;
- }
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- originalServerCnxnFactory);
- }
- }
-
- /**
- * Test case for
- * {@link https://issues.apache.org/jira/browse/ZOOKEEPER-2383}.
- */
- @Test(timeout = 30000)
- public void testFourLetterWords() throws Exception {
- startSimpleZKServer(startupDelayLatch);
- verify("conf", ZK_NOT_SERVING);
- verify("crst", ZK_NOT_SERVING);
- verify("cons", ZK_NOT_SERVING);
- verify("dirs", ZK_NOT_SERVING);
- verify("dump", ZK_NOT_SERVING);
- verify("mntr", ZK_NOT_SERVING);
- verify("stat", ZK_NOT_SERVING);
- verify("srst", ZK_NOT_SERVING);
- verify("wchp", ZK_NOT_SERVING);
- verify("wchc", ZK_NOT_SERVING);
- verify("wchs", ZK_NOT_SERVING);
- verify("isro", "null");
- }
-
- 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));
- }
-
- 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);
- SyncRequestProcessor.setSnapCount(100);
- final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
-
- servcnxnf = ServerCnxnFactory.createFactory(PORT, -1);
- Thread startupThread = new Thread() {
- public void run() {
- try {
- servcnxnf.startup(zks);
- } catch (IOException e) {
- LOG.error("Unexcepted exception during server startup", e);
- // Ignoring exception. If there is an ioexception
- // then one of the following assertion will fail
- } catch (InterruptedException e) {
- LOG.error("Unexcepted exception during server startup", e);
- // 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);
-
- public SimpleZooKeeperServer(File snapDir, File logDir, int tickTime,
- CountDownLatch startupDelayLatch) throws IOException {
- super(snapDir, logDir, tickTime);
- this.startupDelayLatch = startupDelayLatch;
- }
-
- @Override
- public synchronized void startup() {
- try {
- startupInvokedLatch.countDown();
- // Delaying the zk server startup so that
- // ZooKeeperServer#sessionTracker reference won't be
- // initialized. In the defect scenario, while processing the
- // connection request zkServer needs sessionTracker reference,
- // but this is not yet initialized and the server is still in
- // the startup phase, resulting in NPE.
- startupDelayLatch.await();
- } catch (InterruptedException e) {
- Assert.fail(
- "Unexpected InterruptedException while startinng up!");
- }
- super.startup();
- }
-
- @Override
- long createSession(ServerCnxn cnxn, byte[] passwd, int timeout) {
- createSessionInvokedLatch.countDown();
- return super.createSession(cnxn, passwd, timeout);
- }
-
- boolean waitForStartupInvocation(long timeout)
- throws InterruptedException {
- return startupInvokedLatch.await(timeout, TimeUnit.SECONDS);
- }
-
- boolean waitForSessionCreation(long timeout)
- throws InterruptedException {
- return createSessionInvokedLatch.await(timeout, TimeUnit.SECONDS);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerTest.java b/src/java/test/org/apache/zookeeper/server/ZooKeeperServerTest.java
deleted file mode 100644
index 2d7aad1..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZooKeeperServerTest.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-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.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];
-
- files[0] = new File("foo.10027c6de");
- files[1] = new File("foo.10027c6df");
- files[2] = new File("bar.10027c6dd");
- files[3] = new File("foo.10027c6dc");
- files[4] = new File("foo.20027c6dc");
-
- File[] orig = files.clone();
-
- 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));
- }
-
- @Test
- public void testSortDataDirDescending() {
- File[] files = new File[5];
-
- files[0] = new File("foo.10027c6de");
- files[1] = new File("foo.10027c6df");
- files[2] = new File("bar.10027c6dd");
- files[3] = new File("foo.10027c6dc");
- files[4] = new File("foo.20027c6dc");
-
- File[] orig = files.clone();
-
- 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));
- }
-
- @Test
- public void testGetLogFiles() {
- File[] files = new File[5];
-
- files[0] = new File("log.10027c6de");
- files[1] = new File("log.10027c6df");
- files[2] = new File("snapshot.10027c6dd");
- files[3] = new File("log.10027c6dc");
- files[4] = new File("log.20027c6dc");
-
- File[] orig = files.clone();
-
- 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]);
- }
-
- @Test
- public void testForceSyncDefaultEnabled() {
- File file = new File("foo.10027c6de");
- FileTxnLog log = new FileTxnLog(file);
- Assert.assertTrue(log.isForceSync());
- }
-
- @Test
- public void testForceSyncDefaultDisabled() {
- try {
- File file = new File("foo.10027c6de");
- System.setProperty("zookeeper.forceSync","no");
- FileTxnLog log = new FileTxnLog(file);
- Assert.assertFalse(log.isForceSync());
- }
- finally {
- //Reset back to default.
- System.setProperty("zookeeper.forceSync","yes");
- }
- }
-
- @Test
- public void testInvalidSnapshot() {
- File f = null;
- File tmpFileDir = null;
- try {
- tmpFileDir = ClientBase.createTmpDir();
- f = new File(tmpFileDir, "snapshot.0");
- if (!f.exists()) {
- f.createNewFile();
- }
- Assert.assertFalse("Snapshot file size is greater than 9 bytes", Util.isValidSnapshot(f));
- Assert.assertTrue("Can't delete file", f.delete());
- } catch (IOException e) {
- } finally {
- if (null != tmpFileDir) {
- ClientBase.recursiveDelete(tmpFileDir);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZooKeeperThreadTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZooKeeperThreadTest.java b/src/java/test/org/apache/zookeeper/server/ZooKeeperThreadTest.java
deleted file mode 100644
index 2c737fc..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZooKeeperThreadTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper.server;
-
-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 {
-
- public MyThread(String threadName) {
- super(threadName);
- }
-
- public void run() {
- throw new Error();
- }
-
- @Override
- protected void handleException(String thName, Throwable e) {
- runningLatch.countDown();
- }
- }
-
- public class MyCriticalThread extends ZooKeeperCriticalThread {
-
- public MyCriticalThread(String threadName) {
- super(threadName, new ZooKeeperServerListener() {
-
- @Override
- public void notifyStopping(String threadName, int erroCode) {
-
- }
- });
- }
-
- public void run() {
- throw new Error();
- }
-
- @Override
- protected void handleException(String thName, Throwable e) {
- runningLatch.countDown();
- }
- }
-
- /**
- * Test verifies uncaught exception handling of ZooKeeperThread
- */
- @Test(timeout = 30000)
- 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));
-
- 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));
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/ZxidRolloverTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/ZxidRolloverTest.java b/src/java/test/org/apache/zookeeper/server/ZxidRolloverTest.java
deleted file mode 100644
index 838b0a8..0000000
--- a/src/java/test/org/apache/zookeeper/server/ZxidRolloverTest.java
+++ /dev/null
@@ -1,446 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server;
-
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.KeeperException.ConnectionLossException;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-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;
-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;
- private ZooKeeperServer zksLeader;
- private ZooKeeper[] zkClients = new ZooKeeper[3];
- private CountdownWatcher[] zkClientWatchers = new CountdownWatcher[3];
- private int idxLeader;
- private int idxFollower;
-
- private ZooKeeper getClient(int idx) {
- return zkClients[idx-1];
- }
-
- @Before
- public void setUp() throws Exception {
- System.setProperty("zookeeper.admin.enableServer", "false");
-
- // set the snap count to something low so that we force log rollover
- // and verify that is working as part of the epoch rollover.
- SyncRequestProcessor.setSnapCount(7);
-
- qu = new QuorumUtil(1);
- startAll();
-
- for (int i = 0; i < zkClients.length; i++) {
- zkClientWatchers[i] = new CountdownWatcher();
- PeerStruct peer = qu.getPeer(i + 1);
- zkClients[i] = new ZooKeeper(
- "127.0.0.1:" + peer.clientPort,
- 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);
- zkClientWatchers[i].reset();
- }
- }
-
- /**
- * Ensure all clients are able to talk to the service.
- */
- private void checkClientsConnected() throws Exception {
- for (int i = 0; i < zkClients.length; i++) {
- checkClientConnected(i + 1);
- }
- }
-
- /**
- * 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 {
- ZooKeeper zk = getClient(idx);
- if (zk == null) {
- return;
- }
- try {
- Assert.assertNull(zk.exists("/foofoofoo-connected", false));
- } catch (ConnectionLossException e) {
- // second chance...
- // in some cases, leader change in particular, the timing is
- // very tricky to get right in order to assure that the client has
- // disconnected and reconnected. In some cases the client will
- // disconnect, then attempt to reconnect before the server is
- // back, in which case we'll see another connloss on the operation
- // 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));
-
- Assert.assertNull(zk.exists("/foofoofoo-connected", false));
- }
- }
-
- /**
- * Ensure all clients are disconnected from the service.
- */
- private void checkClientsDisconnected() throws Exception {
- for (int i = 0; i < zkClients.length; i++) {
- checkClientDisconnected(i + 1);
- }
- }
-
- /**
- * 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 {
- ZooKeeper zk = getClient(idx);
- if (zk == null) {
- return;
- }
- try {
- Assert.assertNull(zk.exists("/foofoofoo-disconnected", false));
- Assert.fail("expected client to be disconnected");
- } catch (KeeperException e) {
- // success
- }
- }
-
- private void startAll() throws Exception {
- qu.startAll();
- checkLeader();
- // all clients should be connected
- checkClientsConnected();
- }
- 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));
- }
-
- checkLeader();
- // all clients should be connected
- checkClientsConnected();
- }
-
- private void checkLeader() {
- idxLeader = 1;
- while(qu.getPeer(idxLeader).peer.leader == null) {
- idxLeader++;
- }
- idxFollower = (idxLeader == 1 ? 2 : 1);
-
- zksLeader = qu.getPeer(idxLeader).peer.getActiveServer();
- }
-
- private void shutdownAll() throws Exception {
- qu.shutdownAll();
- // 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));
-
- // if idx is the the leader then everyone will get disconnected,
- // otherwise if idx is a follower then just that client will get
- // disconnected
- if (idx == idxLeader) {
- checkClientDisconnected(idx);
- try {
- checkClientsDisconnected();
- } catch (AssertionError e) {
- // the clients may or may not have already reconnected
- // to the recovered cluster, force a check, but ignore
- }
- } else {
- checkClientDisconnected(idx);
- }
- }
-
- /** Reset the next zxid to be near epoch end */
- private void adjustEpochNearEnd() {
- zksLeader.setZxid((zksLeader.getZxid() & 0xffffffff00000000L) | 0xfffffffcL);
- }
-
- @After
- public void tearDown() throws Exception {
- LOG.info("tearDown starting");
- for (int i = 0; i < zkClients.length; i++) {
- zkClients[i].close();
- }
- qu.shutdownAll();
- }
-
- /**
- * Create the znodes, this may fail if the lower 32 roll over, if so
- * wait for the clients to be re-connected after the re-election
- */
- private int createNodes(ZooKeeper zk, int start, int count) throws Exception {
- LOG.info("Creating nodes {} thru {}", start, (start + count));
- 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);
- j++;
- }
- } catch (ConnectionLossException e) {
- // this is ok - the leader has dropped leadership
- waitForClientsConnected();
- }
- return j;
- }
- /**
- * Verify the expected znodes were created and that the last znode, which
- * caused the roll-over, did not.
- */
- 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));
- LOG.error("Exists zxid:{}", Long.toHexString(zk.exists("/foo" + i, false).getCzxid()));
- }
- Assert.assertNull(zk.exists("/foo" + (start + count), false));
- }
-
- /**
- * Prior to the fix this test would hang for a while, then fail with
- * connection loss.
- */
- @Test
- public void testSimpleRolloverFollower() throws Exception {
- adjustEpochNearEnd();
-
- ZooKeeper zk = getClient((idxLeader == 1 ? 2 : 1));
- int countCreated = createNodes(zk, 0, 10);
-
- checkNodes(zk, 0, countCreated);
- }
-
- /**
- * Similar to testSimpleRollover, but ensure the cluster comes back,
- * has the right data, and is able to serve new requests.
- */
- @Test
- public void testRolloverThenRestart() throws Exception {
- ZooKeeper zk = getClient(idxFollower);
-
- int countCreated = createNodes(zk, 0, 10);
-
- adjustEpochNearEnd();
-
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdownAll();
- startAll();
- zk = getClient(idxLeader);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- adjustEpochNearEnd();
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdownAll();
- startAll();
- zk = getClient(idxFollower);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdownAll();
- startAll();
- zk = getClient(idxLeader);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- // sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 60);
- }
-
- /**
- * Similar to testRolloverThenRestart, but ensure a follower comes back,
- * has the right data, and is able to serve new requests.
- */
- @Test
- public void testRolloverThenFollowerRestart() throws Exception {
- ZooKeeper zk = getClient(idxFollower);
-
- int countCreated = createNodes(zk, 0, 10);
-
- adjustEpochNearEnd();
-
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdown(idxFollower);
- start(idxFollower);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- adjustEpochNearEnd();
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdown(idxFollower);
- start(idxFollower);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdown(idxFollower);
- start(idxFollower);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- // sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 60);
- }
-
- /**
- * Similar to testRolloverThenRestart, but ensure leadership can change,
- * comes back, has the right data, and is able to serve new requests.
- */
- @Test
- public void testRolloverThenLeaderRestart() throws Exception {
- ZooKeeper zk = getClient(idxLeader);
-
- int countCreated = createNodes(zk, 0, 10);
-
- adjustEpochNearEnd();
-
- checkNodes(zk, 0, countCreated);
-
- shutdown(idxLeader);
- start(idxLeader);
- zk = getClient(idxLeader);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- adjustEpochNearEnd();
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdown(idxLeader);
- start(idxLeader);
- zk = getClient(idxLeader);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdown(idxLeader);
- start(idxLeader);
- zk = getClient(idxFollower);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- // sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 50);
- }
-
- /**
- * Similar to testRolloverThenRestart, but ensure we can survive multiple
- * epoch rollovers between restarts.
- */
- @Test
- public void testMultipleRollover() throws Exception {
- ZooKeeper zk = getClient(idxFollower);
-
- int countCreated = createNodes(zk, 0, 10);
-
- adjustEpochNearEnd();
-
- countCreated += createNodes(zk, countCreated, 10);
-
- adjustEpochNearEnd();
-
- countCreated += createNodes(zk, countCreated, 10);
-
- adjustEpochNearEnd();
-
- countCreated += createNodes(zk, countCreated, 10);
-
- adjustEpochNearEnd();
-
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdownAll();
- startAll();
- zk = getClient(idxFollower);
-
- adjustEpochNearEnd();
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- shutdown(idxLeader);
- start(idxLeader);
- zk = getClient(idxFollower);
-
- checkNodes(zk, 0, countCreated);
- countCreated += createNodes(zk, countCreated, 10);
-
- // sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 70);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/admin/CommandResponseTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/admin/CommandResponseTest.java b/src/java/test/org/apache/zookeeper/server/admin/CommandResponseTest.java
deleted file mode 100644
index ab8c258..0000000
--- a/src/java/test/org/apache/zookeeper/server/admin/CommandResponseTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server.admin;
-
-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 {
- r = new CommandResponse("makemeasandwich", "makeityourself");
- }
-
- @Test public void testGetters() {
- assertEquals("makemeasandwich", r.getCommand());
- assertEquals("makeityourself", r.getError());
- }
-
- @Test public void testMap() {
- r.put("missing", "sudo");
- Map<String, Object> m = new HashMap<String, Object>();
- m.put("origin", "xkcd");
- m.put("url", "http://xkcd.com/149/");
- r.putAll(m);
-
- Map<String, Object> rmap = r.toMap();
- assertEquals(5, rmap.size());
- assertEquals("makemeasandwich", rmap.get(CommandResponse.KEY_COMMAND));
- assertEquals("makeityourself", rmap.get(CommandResponse.KEY_ERROR));
- assertEquals("sudo", rmap.get("missing"));
- assertEquals("xkcd", rmap.get("origin"));
- assertEquals("http://xkcd.com/149/", rmap.get("url"));
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/3ce1b18b/src/java/test/org/apache/zookeeper/server/admin/CommandsTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/admin/CommandsTest.java b/src/java/test/org/apache/zookeeper/server/admin/CommandsTest.java
deleted file mode 100644
index 762547f..0000000
--- a/src/java/test/org/apache/zookeeper/server/admin/CommandsTest.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.server.admin;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-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.HashMap;
-import java.util.Map;
-
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.ServerStats;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.apache.zookeeper.server.quorum.BufferStats;
-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
- * and that there are no extra entries.
- *
- * @param cmdName
- * - the primary name of the command
- * @param kwargs
- * - keyword arguments to the command
- * @param keys
- * - the keys that are expected in the returned Map
- * @param types
- * - the classes of the values in the returned Map. types[i] is
- * the type of the value for keys[i].
- * @throws IOException
- * @throws 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();
-
- assertTrue(result.containsKey("command"));
- // This is only true because we're setting cmdName to the primary name
- assertEquals(cmdName, result.remove("command"));
- assertTrue(result.containsKey("error"));
- assertNull("error: " + result.get("error"), result.remove("error"));
-
- for (Field field : fields) {
- String k = field.key;
- 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("Result from command " + cmdName + " contains extra fields: " + result,
- result.isEmpty());
- }
-
- 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));
- }
-
- @Test
- public void testConnections() throws IOException, InterruptedException {
- testCommand("connections",
- new Field("connections", Iterable.class),
- new Field("secure_connections", Iterable.class)
- );
- }
-
- @Test
- public void testConnectionStatReset() throws IOException, InterruptedException {
- testCommand("connection_stat_reset");
- }
-
- @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));
- }
-
- @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));
- }
-
- @Test
- public void testGetTraceMask() throws IOException, InterruptedException {
- 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));
- }
-
- @Test
- public void testMonitor() throws IOException, InterruptedException {
- testCommand("monitor",
- new Field("version", String.class),
- new Field("avg_latency", Long.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));
- }
-
- @Test
- public void testRuok() throws IOException, InterruptedException {
- testCommand("ruok");
- }
-
- @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));
- }
-
- @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));
- }
-
- @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));
- }
-
- @Test
- public void testStatReset() throws IOException, InterruptedException {
- testCommand("stat_reset");
- }
-
- @Test
- public void testWatches() throws IOException, InterruptedException {
- 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));
- }
-
- @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));
- }
-
- @Test
- public void testConsCommandSecureOnly() {
- // Arrange
- Commands.ConsCommand cmd = new Commands.ConsCommand();
- ZooKeeperServer zkServer = mock(ZooKeeperServer.class);
- ServerCnxnFactory cnxnFactory = mock(ServerCnxnFactory.class);
- when(zkServer.getSecureServerCnxnFactory()).thenReturn(cnxnFactory);
-
- // Act
- CommandResponse response = cmd.run(zkServer, null);
-
- // Assert
- assertThat(response.toMap().containsKey("connections"), is(true));
- assertThat(response.toMap().containsKey("secure_connections"), is(true));
- }
-}