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/19 12:40:26 UTC
[28/51] [partial] zookeeper git commit: ZOOKEEPER-3032: MAVEN
MIGRATION - zookeeper-server
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SSLTest.java.orig
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SSLTest.java.orig b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SSLTest.java.orig
deleted file mode 100644
index 16911b7..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SSLTest.java.orig
+++ /dev/null
@@ -1,130 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * 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.test;
-
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.client.ZKClientConfig;
-import org.apache.zookeeper.common.ZKConfig;
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class SSLTest extends QuorumPeerTestBase {
-
- @Before
- public void setup() {
- String testDataPath = System.getProperty("test.data.dir", "build/test/data");
- 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(ZKClientConfig.SECURE_CLIENT, "true");
- System.setProperty(ZKConfig.SSL_KEYSTORE_LOCATION, testDataPath + "/ssl/testKeyStore.jks");
- System.setProperty(ZKConfig.SSL_KEYSTORE_PASSWD, "testpass");
- System.setProperty(ZKConfig.SSL_TRUSTSTORE_LOCATION, testDataPath + "/ssl/testTrustStore.jks");
- System.setProperty(ZKConfig.SSL_TRUSTSTORE_PASSWD, "testpass");
- }
-
- @After
- public void teardown() throws Exception {
- System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
- System.clearProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET);
- System.clearProperty(ZKClientConfig.SECURE_CLIENT);
- System.clearProperty(ZKConfig.SSL_KEYSTORE_LOCATION);
- System.clearProperty(ZKConfig.SSL_KEYSTORE_PASSWD);
- System.clearProperty(ZKConfig.SSL_TRUSTSTORE_LOCATION);
- System.clearProperty(ZKConfig.SSL_TRUSTSTORE_PASSWD);
- }
-
- /**
- * This test checks that SSL works in cluster setup of ZK servers, which includes:
- * 1. setting "secureClientPort" in "zoo.cfg" file.
- * 2. setting jvm flags for serverCnxn, keystore, truststore.
- * Finally, a zookeeper client should be able to connect to the secure port and
- * communicate with server via secure connection.
- * <p/>
- * Note that in this test a ZK server has two ports -- clientPort and secureClientPort.
- */
- @Test
- public void testSecureQuorumServer() throws Exception {
- final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
- final Integer secureClientPorts[] = new Integer[SERVER_COUNT];
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < SERVER_COUNT; i++) {
- clientPorts[i] = PortAssignment.unique();
- secureClientPorts[i] = PortAssignment.unique();
- String server = String.format("server.%d=localhost:%d:%d:participant;localhost:%d",
- i, PortAssignment.unique(), PortAssignment.unique(), clientPorts[i]);
- sb.append(server + "\n");
- }
- String quorumCfg = sb.toString();
-
-
- MainThread[] mt = new MainThread[SERVER_COUNT];
- for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, quorumCfg, secureClientPorts[i], true);
- mt[i].start();
- }
-
- // Servers have been set up. Now go test if secure connection is successful.
- for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], TIMEOUT));
-
- ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + secureClientPorts[i], TIMEOUT);
- // Do a simple operation to make sure the connection is fine.
- zk.create("/test", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.delete("/test", -1);
- zk.close();
- }
-
- for (int i = 0; i < mt.length; i++) {
- mt[i].shutdown();
- }
- }
-
-
- /**
- * Developers might use standalone mode (which is the default for one server).
- * This test checks SSL works in standalone mode of ZK server.
- * <p/>
- * Note that in this test the Zk server has only secureClientPort
- */
- @Test
- public void testSecureStandaloneServer() throws Exception {
- Integer secureClientPort = PortAssignment.unique();
- MainThread mt = new MainThread(MainThread.UNSET_MYID, "", secureClientPort, false);
- mt.start();
-
- ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + secureClientPort, TIMEOUT);
- zk.create("/test", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.delete("/test", -1);
- zk.close();
- mt.shutdown();
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java
deleted file mode 100644
index c007022..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java
+++ /dev/null
@@ -1,166 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooDefs.Perms;
-import org.apache.zookeeper.client.ZKClientConfig;
-import org.apache.zookeeper.client.ZooKeeperSaslClient;
-import org.apache.zookeeper.data.ACL;
-import org.apache.zookeeper.data.Id;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SaslAuthDesignatedClientTest extends ClientBase {
- static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
- "MyZookeeperClient");
-
- try {
- File tmpDir = createTmpDir();
- File saslConfFile = new File(tmpDir, "jaas.conf");
- FileWriter fwriter = new FileWriter(saslConfFile);
-
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_myuser=\"mypassword\";\n" +
- "};\n" +
- "Client {\n" + /* this 'Client' section has an incorrect password, but we're not configured
- to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
- use the 'MyZookeeperClient' section below, which has the correct password).*/
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"wrongpassword\";\n" +
- "};" +
- "MyZookeeperClient {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"mypassword\";\n" +
- "};" + "\n");
- fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
- // could not create tmp directory to hold JAAS conf file : test will fail now.
- }
- }
-
- @Test
- public void testAuth() throws Exception {
- ZooKeeper zk = createClient();
- try {
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Thread.sleep(1000);
- } catch (KeeperException e) {
- Assert.fail("test failed :" + e);
- }
- finally {
- zk.close();
- }
- }
-
- @Test
- public void testSaslConfig() throws Exception {
- ZooKeeper zk = createClient();
- try {
- zk.getChildren("/", false);
- Assert.assertFalse(zk.getSaslClient().
- clientTunneledAuthenticationInProgress());
- Assert.assertEquals(zk.getSaslClient().getSaslState(),
- ZooKeeperSaslClient.SaslState.COMPLETE);
- Assert.assertNotNull(
- javax.security.auth.login.Configuration.getConfiguration().
- getAppConfigurationEntry("MyZookeeperClient"));
- Assert.assertSame(zk.getSaslClient().getLoginContext(),
- "MyZookeeperClient");
- } catch (KeeperException e) {
- Assert.fail("test failed :" + e);
- } finally {
- zk.close();
- }
- }
-
- @Test
- public void testReadAccessUser() throws Exception {
- System.setProperty("zookeeper.letAnySaslUserDoX","anyone");
- ZooKeeper zk = createClient();
- List<ACL> aclList = new ArrayList<ACL>();
- ACL acl = new ACL(Perms.ADMIN | Perms.CREATE | Perms.WRITE | Perms.DELETE, new Id("sasl", "fakeuser"));
- ACL acl1 = new ACL(Perms.READ, new Id("sasl", "anyone"));
- aclList.add(acl);
- aclList.add(acl1);
- try {
- zk.create("/abc", "testData".getBytes(), aclList, CreateMode.PERSISTENT);
- } catch (KeeperException e) {
- Assert.fail("Unable to create znode");
- }
- zk.close();
- Thread.sleep(100);
-
- // try to access it with different user (myuser)
- zk = createClient();
-
- try {
- zk.setData("/abc", "testData1".getBytes(), -1);
- Assert.fail("Should not be able to set data");
- } catch (KeeperException.NoAuthException e) {
- // success
- }
-
- try {
- byte [] bytedata = zk.getData("/abc", null, null);
- String data = new String(bytedata);
- Assert.assertTrue("testData".equals(data));
- } catch (KeeperException e) {
- Assert.fail("failed to get data");
- }
-
- zk.close();
- Thread.sleep(100);
-
- // disable Client Sasl
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, "false");
-
- try {
- zk = createClient();
- try {
- zk.getData("/abc", null, null);
- Assert.fail("Should not be able to read data when not authenticated");
- } catch (KeeperException.NoAuthException e) {
- // success
- }
- zk.close();
- } finally {
- // enable Client Sasl
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- "true");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java
deleted file mode 100644
index aa30870..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java
+++ /dev/null
@@ -1,104 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.server.ZooKeeperSaslServer;
-import org.apache.zookeeper.JaasConfiguration;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SaslAuthDesignatedServerTest extends ClientBase {
- public static int AUTHENTICATION_TIMEOUT = 30000;
-
- static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty(ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY, "MyZookeeperServer");
-
- JaasConfiguration conf = new JaasConfiguration();
-
- /* this 'Server' section has an incorrect password, but we're not configured
- * to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...)
- * to use the 'MyZookeeperServer' section below, which has the correct password).
- */
- conf.addSection("Server", "org.apache.zookeeper.server.auth.DigestLoginModule",
- "user_myuser", "wrongpassword");
-
- conf.addSection("MyZookeeperServer", "org.apache.zookeeper.server.auth.DigestLoginModule",
- "user_myuser", "mypassword");
-
- conf.addSection("Client", "org.apache.zookeeper.server.auth.DigestLoginModule",
- "username", "myuser", "password", "mypassword");
-
- javax.security.auth.login.Configuration.setConfiguration(conf);
- }
-
- private AtomicInteger authFailed = new AtomicInteger(0);
-
- private class MyWatcher extends CountdownWatcher {
- volatile CountDownLatch authCompleted;
-
- @Override
- synchronized public void reset() {
- authCompleted = new CountDownLatch(1);
- super.reset();
- }
-
- @Override
- public synchronized void process(WatchedEvent event) {
- if (event.getState() == KeeperState.AuthFailed) {
- authFailed.incrementAndGet();
- authCompleted.countDown();
- } else if (event.getState() == KeeperState.SaslAuthenticated) {
- authCompleted.countDown();
- } else {
- super.process(event);
- }
- }
- }
-
- @Test
- public void testAuth() throws Exception {
- MyWatcher watcher = new MyWatcher();
- ZooKeeper zk = createClient(watcher);
- watcher.authCompleted.await(AUTHENTICATION_TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(authFailed.get(), 0);
-
- try {
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- } catch (KeeperException e) {
- Assert.fail("test failed :" + e);
- }
- finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java
deleted file mode 100644
index df8c903..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java
+++ /dev/null
@@ -1,92 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.TestableZooKeeper;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SaslAuthFailDesignatedClientTest extends ClientBase {
- static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
- "MyZookeeperClient");
-
- try {
- File tmpDir = createTmpDir();
- File saslConfFile = new File(tmpDir, "jaas.conf");
- FileWriter fwriter = new FileWriter(saslConfFile);
-
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_myuser=\"mypassword\";\n" +
- "};\n" +
- "Client {\n" + /* this 'Client' section has the correct password, but we're not configured
- to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
- use the 'MyZookeeperClient' section, which has an incorrect password).*/
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"mypassword\";\n" +
- "};" +
- "MyZookeeperClient {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"wrongpassword\";\n" +
- "};" + "\n");
- fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
- // could not create tmp directory to hold JAAS conf file : test will fail now.
- }
- }
-
-
- @Test
- public void testAuth() throws Exception {
- // Cannot use createClient here because server may close session before
- // JMXEnv.ensureAll is called which will fail the test case
- CountdownWatcher watcher = new CountdownWatcher();
- TestableZooKeeper zk = new TestableZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher);
- if (!watcher.clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS))
- {
- Assert.fail("Unable to connect to server");
- }
- try {
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have gotten exception.");
- } catch (KeeperException e) {
- // ok, exception as expected.
- LOG.info("Got exception as expected: " + e);
- }
- finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailNotifyTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailNotifyTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailNotifyTest.java
deleted file mode 100644
index 2b00d86..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailNotifyTest.java
+++ /dev/null
@@ -1,98 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.TestableZooKeeper;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Test;
-import org.junit.Assert;
-
-public class SaslAuthFailNotifyTest extends ClientBase {
- static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty("zookeeper.allowSaslFailedClients","true");
-
- try {
- File tmpDir = createTmpDir();
- File saslConfFile = new File(tmpDir, "jaas.conf");
- FileWriter fwriter = new FileWriter(saslConfFile);
-
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_super=\"test\";\n" +
- "};\n" +
- "Client {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"super\"\n" +
- " password=\"test1\";\n" + // NOTE: wrong password ('test' != 'test1') : this is to test SASL authentication failure.
- "};" + "\n");
- fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
- // could not create tmp directory to hold JAAS conf file.
- }
- }
-
- private AtomicInteger authFailed = new AtomicInteger(0);
-
- @Override
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
- MyWatcher watcher = new MyWatcher();
- return createClient(watcher, hp);
- }
-
- private class MyWatcher extends CountdownWatcher {
- @Override
- public synchronized void process(WatchedEvent event) {
- if (event.getState() == KeeperState.AuthFailed) {
- synchronized(authFailed) {
- authFailed.incrementAndGet();
- authFailed.notify();
- }
- }
- else {
- super.process(event);
- }
- }
- }
-
- @Test
- public void testBadSaslAuthNotifiesWatch() throws Exception {
- ZooKeeper zk = createClient();
- // wait for authFailed event from client's EventThread.
- synchronized(authFailed) {
- authFailed.wait();
- }
- Assert.assertEquals(authFailed.get(),1);
- zk.close();
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java
deleted file mode 100644
index 33a505e..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java
+++ /dev/null
@@ -1,76 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.TestableZooKeeper;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Test;
-import org.junit.Assert;
-
-public class SaslAuthFailTest extends ClientBase {
- static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty("zookeeper.allowSaslFailedClients","true");
-
- try {
- File tmpDir = createTmpDir();
- File saslConfFile = new File(tmpDir, "jaas.conf");
- FileWriter fwriter = new FileWriter(saslConfFile);
-
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_super=\"test\";\n" +
- "};\n" +
- "Client {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"super\"\n" +
- " password=\"test1\";\n" + // NOTE: wrong password ('test' != 'test1') : this is to test SASL authentication failure.
- "};" + "\n");
- fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
- // could not create tmp directory to hold JAAS conf file.
- }
- }
-
- @Test
- public void testAuthFail() throws Exception {
- ZooKeeper zk = createClient();
- try {
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have gotten exception.");
- } catch(Exception e ) {
- // ok, exception as expected.
- LOG.info("Got exception as expected: " + e);
- } finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java
deleted file mode 100644
index ee01387..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java
+++ /dev/null
@@ -1,81 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-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.client.ZKClientConfig;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SaslAuthMissingClientConfigTest extends ClientBase {
- static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- // This configuration section 'MyZookeeperClient', is missing from the JAAS configuration.
- // As a result, SASL authentication should fail, which is tested by this test (testAuth()).
- System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
- "MyZookeeperClient");
-
- try {
- File tmpDir = createTmpDir();
- File saslConfFile = new File(tmpDir, "jaas.conf");
- FileWriter fwriter = new FileWriter(saslConfFile);
-
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_myuser=\"mypassword\";\n" +
- "};\n" +
- "Client {\n" + /* this 'Client' section has the correct password, but we're not configured
- to use it - we're configured instead by the above
- System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
- use the (nonexistent) 'MyZookeeperClient' section. */
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"mypassword\";\n" +
- "};\n");
- fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
- // could not create tmp directory to hold JAAS conf file : test will fail now.
- }
- }
-
- @Test
- public void testAuth() throws Exception {
- ZooKeeper zk = createClient();
- try {
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have gotten exception.");
- } catch (KeeperException e) {
- // ok, exception as expected.
- LOG.info("Got exception as expected: " + e);
- }
- finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslClientTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslClientTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslClientTest.java
deleted file mode 100644
index 95bf2f6..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslClientTest.java
+++ /dev/null
@@ -1,69 +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.test;
-
-
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-public class SaslClientTest extends ZKTestCase {
-
- private String existingPropertyValue = null;
-
- @Before
- public void setUp() {
- existingPropertyValue = System
- .getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY);
- }
-
- @After
- public void tearDown() {
- // Restore the System property if it was set previously
- if (existingPropertyValue != null) {
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- existingPropertyValue);
- }
- }
-
- @Test
- public void testSaslClientDisabled() {
- System.clearProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY);
- Assert.assertTrue("SASL client disabled",
- new ZKClientConfig().isSaslClientEnabled());
-
- for (String value : Arrays.asList("true", "TRUE")) {
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- value);
- Assert.assertTrue("SASL client disabled",
- new ZKClientConfig().isSaslClientEnabled());
- }
-
- for (String value : Arrays.asList("false", "FALSE")) {
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- value);
- Assert.assertFalse("SASL client disabled",
- new ZKClientConfig().isSaslClientEnabled());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java
deleted file mode 100644
index 894c0f5..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java
+++ /dev/null
@@ -1,136 +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.test;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.TestableZooKeeper;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.apache.zookeeper.ZooDefs.Perms;
-import org.apache.zookeeper.data.ACL;
-import org.apache.zookeeper.data.Id;
-import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
-import org.junit.Assert;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class SaslSuperUserTest extends ClientBase {
- private static Id otherSaslUser = new Id ("sasl", "joe");
- private static Id otherDigestUser;
- private static String oldAuthProvider;
- private static String oldLoginConfig;
- private static String oldSuperUser;
-
- @BeforeClass
- public static void setupStatic() throws Exception {
- oldAuthProvider = System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
-
- File tmpDir = createTmpDir();
- File saslConfFile = new File(tmpDir, "jaas.conf");
- FileWriter fwriter = new FileWriter(saslConfFile);
-
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_super_duper=\"test\";\n" +
- "};\n" +
- "Client {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"super_duper\"\n" +
- " password=\"test\";\n" +
- "};" + "\n");
- fwriter.close();
- oldLoginConfig = System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- oldSuperUser = System.setProperty("zookeeper.superUser","super_duper");
- otherDigestUser = new Id ("digest", DigestAuthenticationProvider.generateDigest("jack:jack"));
- }
-
- @AfterClass
- public static void cleanupStatic() {
- if (oldAuthProvider != null) {
- System.setProperty("zookeeper.authProvider.1", oldAuthProvider);
- } else {
- System.clearProperty("zookeeper.authProvider.1");
- }
- oldAuthProvider = null;
-
- if (oldLoginConfig != null) {
- System.setProperty("java.security.auth.login.config", oldLoginConfig);
- } else {
- System.clearProperty("java.security.auth.login.config");
- }
- oldLoginConfig = null;
-
- if (oldSuperUser != null) {
- System.setProperty("zookeeper.superUser", oldSuperUser);
- } else {
- System.clearProperty("zookeeper.superUser");
- }
- oldSuperUser = null;
- }
-
- private AtomicInteger authFailed = new AtomicInteger(0);
-
- @Override
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
- MyWatcher watcher = new MyWatcher();
- return createClient(watcher, hp);
- }
-
- private class MyWatcher extends CountdownWatcher {
- @Override
- public synchronized void process(WatchedEvent event) {
- if (event.getState() == KeeperState.AuthFailed) {
- authFailed.incrementAndGet();
- }
- else {
- super.process(event);
- }
- }
- }
-
- @Test
- public void testSuperIsSuper() throws Exception {
- ZooKeeper zk = createClient();
- try {
- zk.create("/digest_read", null, Arrays.asList(new ACL(Perms.READ, otherDigestUser)), CreateMode.PERSISTENT);
- zk.create("/digest_read/sub", null, Arrays.asList(new ACL(Perms.READ, otherDigestUser)), CreateMode.PERSISTENT);
- zk.create("/sasl_read", null, Arrays.asList(new ACL(Perms.READ, otherSaslUser)), CreateMode.PERSISTENT);
- zk.create("/sasl_read/sub", null, Arrays.asList(new ACL(Perms.READ, otherSaslUser)), CreateMode.PERSISTENT);
- zk.delete("/digest_read/sub", -1);
- zk.delete("/digest_read", -1);
- zk.delete("/sasl_read/sub", -1);
- zk.delete("/sasl_read", -1);
- //If the test failes it will most likely fail with a NoAuth exception before it ever gets to this assertion
- Assert.assertEquals(authFailed.get(), 0);
- } finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java
deleted file mode 100644
index 67ece2a..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java
+++ /dev/null
@@ -1,129 +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.test;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.Socket;
-
-import org.apache.zookeeper.server.NIOServerCnxnFactory;
-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 ServerCnxnTest extends ClientBase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(ServerCnxnTest.class);
-
- private static int cnxnTimeout = 1000;
-
- @Before
- public void setUp() throws Exception {
- System.setProperty(
- NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT,
- Integer.toString(cnxnTimeout));
- super.setUp();
- }
-
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- System.clearProperty(
- NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT);
- }
-
- @Test
- public void testServerCnxnExpiry() throws Exception {
- verify("ruok", "imok");
-
- // Expiry time is (now/cnxnTimeout + 1)*cnxnTimeout
- // Range is (now + cnxnTimeout) to (now + 2*cnxnTimeout)
- // Add 1s buffer to be safe.
- String resp = sendRequest("ruok", 2 * cnxnTimeout + 1000);
- Assert.assertEquals("Connection should have closed", "", resp);
- }
-
-
- private void verify(String cmd, String expected) throws IOException {
- String resp = sendRequest(cmd, 0);
- LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
- Assert.assertTrue(resp.contains(expected));
- }
-
- private String sendRequest(String cmd, int delay) throws IOException {
- HostPort hpobj = ClientBase.parseHostPortList(hostPort).get(0);
- return send4LetterWord(hpobj.host, hpobj.port, cmd, delay);
- }
-
- private static String send4LetterWord(
- String host, int port, String cmd, int delay) throws IOException
- {
- LOG.info("connecting to " + host + " " + port);
- Socket sock = new Socket(host, port);
- BufferedReader reader = null;
- try {
- try {
- LOG.info("Sleeping for " + delay + "ms");
- Thread.sleep(delay);
- } catch (InterruptedException e) {
- // ignore
- }
-
- OutputStream outstream = sock.getOutputStream();
- outstream.write(cmd.getBytes());
- outstream.flush();
- // this replicates NC - close the output stream before reading
- sock.shutdownOutput();
-
- reader =
- new BufferedReader(
- new InputStreamReader(sock.getInputStream()));
- StringBuilder sb = readLine(reader);
- return sb.toString();
- } finally {
- sock.close();
- if (reader != null) {
- reader.close();
- }
- }
- }
-
- private static StringBuilder readLine(BufferedReader reader) {
- StringBuilder sb = new StringBuilder();
- String line;
- try {
- while((line = reader.readLine()) != null) {
- sb.append(line + "\n");
- }
- } catch (IOException ioe) {
- // During connection expiry the server will close the connection.
- // After the socket is closed, when the client tries to read a
- // line of text it will throw java.net.SocketException.
- // @see jira issue ZOOKEEPER-1862
- LOG.info("Connnection is expired", ioe);
- }
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java
deleted file mode 100644
index 22a1518..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java
+++ /dev/null
@@ -1,105 +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.test;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Socket;
-
-
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooDefs.OpCode;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.proto.ConnectRequest;
-import org.apache.zookeeper.proto.CreateRequest;
-import org.apache.zookeeper.proto.RequestHeader;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SessionInvalidationTest extends ClientBase {
- /**
- * Test solution for ZOOKEEPER-1208. Verify that operations are not
- * accepted after a close session.
- *
- * We're using our own marshalling here in order to force an operation
- * after the session is closed (ZooKeeper.class will not allow this). Also
- * by filling the pipe with operations it increases the likelyhood that
- * the server will process the create before FinalRequestProcessor
- * removes the session from the tracker.
- */
- @Test
- public void testCreateAfterCloseShouldFail() throws Exception {
- for (int i = 0; i < 10; i++) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
-
- // open a connection
- boa.writeInt(44, "len");
- ConnectRequest conReq = new ConnectRequest(0, 0, 30000, 0, new byte[16]);
- conReq.serialize(boa, "connect");
-
- // close connection
- boa.writeInt(8, "len");
- RequestHeader h = new RequestHeader(1, ZooDefs.OpCode.closeSession);
- h.serialize(boa, "header");
-
- // create ephemeral znode
- boa.writeInt(52, "len"); // We'll fill this in later
- RequestHeader header = new RequestHeader(2, OpCode.create);
- header.serialize(boa, "header");
- CreateRequest createReq = new CreateRequest("/foo" + i, new byte[0],
- Ids.OPEN_ACL_UNSAFE, 1);
- createReq.serialize(boa, "request");
- baos.close();
-
- System.out.println("Length:" + baos.toByteArray().length);
-
- String hp[] = hostPort.split(":");
- Socket sock = new Socket(hp[0], Integer.parseInt(hp[1]));
- InputStream resultStream = null;
- try {
- OutputStream outstream = sock.getOutputStream();
- byte[] data = baos.toByteArray();
- outstream.write(data);
- outstream.flush();
-
- resultStream = sock.getInputStream();
- byte[] b = new byte[10000];
- int len;
- while ((len = resultStream.read(b)) >= 0) {
- // got results
- System.out.println("gotlen:" + len);
- }
- } finally {
- if (resultStream != null) {
- resultStream.close();
- }
- sock.close();
- }
- }
-
- ZooKeeper zk = createClient();
- Assert.assertEquals(1, zk.getChildren("/", false).size());
-
- zk.close();
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTest.java
deleted file mode 100644
index 889b65e..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTest.java
+++ /dev/null
@@ -1,412 +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.test;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.AsyncCallback;
-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.Watcher.Event.EventType;
-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.data.Stat;
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class SessionTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory.getLogger(SessionTest.class);
-
- private static final String HOSTPORT = "127.0.0.1:" +
- PortAssignment.unique();
-
- private ServerCnxnFactory serverFactory;
- private ZooKeeperServer zs;
-
- private CountDownLatch startSignal;
-
- File tmpDir;
-
- private final int TICK_TIME = 3000;
-
- @Before
- public void setUp() throws Exception {
- if (tmpDir == null) {
- tmpDir = ClientBase.createTmpDir();
- }
-
- ClientBase.setupTestEnv();
- zs = new ZooKeeperServer(tmpDir, tmpDir, TICK_TIME);
-
- final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
- serverFactory = ServerCnxnFactory.createFactory(PORT, -1);
- serverFactory.startup(zs);
-
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT,
- CONNECTION_TIMEOUT));
- }
-
- @After
- public void tearDown() throws Exception {
- serverFactory.shutdown();
- zs.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- CONNECTION_TIMEOUT));
- }
-
- private static class CountdownWatcher implements Watcher {
- volatile CountDownLatch clientConnected = new CountDownLatch(1);
-
- public void process(WatchedEvent event) {
- if (event.getState() == KeeperState.SyncConnected) {
- clientConnected.countDown();
- }
- }
- }
-
- private DisconnectableZooKeeper createClient()
- throws IOException, InterruptedException
- {
- CountdownWatcher watcher = new CountdownWatcher();
- return createClient(CONNECTION_TIMEOUT, watcher);
- }
-
- private DisconnectableZooKeeper createClient(int timeout)
- throws IOException, InterruptedException
- {
- CountdownWatcher watcher = new CountdownWatcher();
- return createClient(timeout, watcher);
- }
-
- private DisconnectableZooKeeper createClient(int timeout,
- CountdownWatcher watcher)
- throws IOException, InterruptedException
- {
- DisconnectableZooKeeper zk =
- new DisconnectableZooKeeper(HOSTPORT, timeout, watcher);
- if(!watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS)) {
- Assert.fail("Unable to connect to server");
- }
-
- return zk;
- }
-
-// FIXME this test is Assert.failing due to client close race condition fixing in separate patch for ZOOKEEPER-63
-// /**
-// * this test checks to see if the sessionid that was created for the
-// * first zookeeper client can be reused for the second one immidiately
-// * after the first client closes and the new client resues them.
-// * @throws IOException
-// * @throws InterruptedException
-// * @throws KeeperException
-// */
-// public void testSessionReuse() throws IOException, InterruptedException {
-// ZooKeeper zk = createClient();
-//
-// long sessionId = zk.getSessionId();
-// byte[] passwd = zk.getSessionPasswd();
-// zk.close();
-//
-// zk.close();
-//
-// LOG.info("Closed first session");
-//
-// startSignal = new CountDownLatch(1);
-// zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this,
-// sessionId, passwd);
-// startSignal.await();
-//
-// LOG.info("Opened reuse");
-//
-// Assert.assertEquals(sessionId, zk.getSessionId());
-//
-// zk.close();
-// }
-
- private class MyWatcher implements Watcher {
- private String name;
- public MyWatcher(String name) {
- this.name = name;
- }
- public void process(WatchedEvent event) {
- LOG.info(name + " event:" + event.getState() + " "
- + event.getType() + " " + event.getPath());
- if (event.getState() == KeeperState.SyncConnected
- && startSignal != null && startSignal.getCount() > 0)
- {
- startSignal.countDown();
- }
- }
- }
-
- /**
- * This test verifies that when the session id is reused, and the original
- * client is disconnected, but not session closed, that the server
- * will remove ephemeral nodes created by the original session.
- */
- @Test
- public void testSession()
- throws IOException, InterruptedException, KeeperException
- {
- DisconnectableZooKeeper zk = createClient();
- zk.create("/e", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- LOG.info("zk with session id 0x" + Long.toHexString(zk.getSessionId())
- + " was destroyed!");
-
- // disconnect the client by killing the socket, not sending the
- // session disconnect to the server as usual. This allows the test
- // to verify disconnect handling
- zk.disconnect();
-
- Stat stat = new Stat();
- startSignal = new CountDownLatch(1);
- zk = new DisconnectableZooKeeper(HOSTPORT, CONNECTION_TIMEOUT,
- new MyWatcher("testSession"), zk.getSessionId(),
- zk.getSessionPasswd());
- startSignal.await();
-
- LOG.info("zk with session id 0x" + Long.toHexString(zk.getSessionId())
- + " was created!");
- zk.getData("/e", false, stat);
- LOG.info("After get data /e");
- zk.close();
-
- zk = createClient();
- Assert.assertEquals(null, zk.exists("/e", false));
- LOG.info("before close zk with session id 0x"
- + Long.toHexString(zk.getSessionId()) + "!");
- zk.close();
- try {
- zk.getData("/e", false, stat);
- Assert.fail("Should have received a SessionExpiredException");
- } catch(KeeperException.SessionExpiredException e) {}
-
- AsyncCallback.DataCallback cb = new AsyncCallback.DataCallback() {
- String status = "not done";
- public void processResult(int rc, String p, Object c, byte[] b, Stat s) {
- synchronized(this) { status = KeeperException.Code.get(rc).toString(); this.notify(); }
- }
- public String toString() { return status; }
- };
- zk.getData("/e", false, cb, null);
- synchronized(cb) {
- if (cb.toString().equals("not done")) {
- cb.wait(1000);
- }
- }
- Assert.assertEquals(KeeperException.Code.SESSIONEXPIRED.toString(), cb.toString());
- }
-
- /**
- * Make sure that we cannot have two connections with the same
- * session id.
- *
- * @throws IOException
- * @throws InterruptedException
- * @throws KeeperException
- */
- @Test
- public void testSessionMove() throws Exception {
- String hostPorts[] = HOSTPORT.split(",");
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0],
- CONNECTION_TIMEOUT, new MyWatcher("0"));
- zk.create("/sessionMoveTest", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- // we want to loop through the list twice
- for(int i = 0; i < hostPorts.length*2; i++) {
- zk.dontReconnect();
- // This should stomp the zk handle
- DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(
- hostPorts[(i+1)%hostPorts.length],
- CONNECTION_TIMEOUT,
- new MyWatcher(Integer.toString(i+1)),
- zk.getSessionId(),
- zk.getSessionPasswd());
- final int result[] = new int[1];
- result[0] = Integer.MAX_VALUE;
- zknew.sync("/", new AsyncCallback.VoidCallback() {
- public void processResult(int rc, String path, Object ctx) {
- synchronized(result) { result[0] = rc; result.notify(); }
- }
- }, null);
- synchronized(result) {
- if(result[0] == Integer.MAX_VALUE) {
- result.wait(5000);
- }
- }
- LOG.info(hostPorts[(i+1)%hostPorts.length] + " Sync returned " + result[0]);
- Assert.assertTrue(result[0] == KeeperException.Code.OK.intValue());
- zknew.setData("/", new byte[1], -1);
- try {
- zk.setData("/", new byte[1], -1);
- Assert.fail("Should have lost the connection");
- } catch(KeeperException.ConnectionLossException e) {
- LOG.info("Got connection loss exception as expected");
- }
- //zk.close();
- zk = zknew;
- }
- zk.close();
- }
- /**
- * This test makes sure that duplicate state changes are not communicated
- * to the client watcher. For example we should not notify state as
- * "disconnected" if the watch has already been disconnected. In general
- * we don't consider a dup state notification if the event type is
- * not "None" (ie non-None communicates an event).
- */
- @Test
- public void testSessionStateNoDupStateReporting()
- throws IOException, InterruptedException, KeeperException
- {
- final int TIMEOUT = 3000;
- DupWatcher watcher = new DupWatcher();
- ZooKeeper zk = createClient(TIMEOUT, watcher);
-
- // shutdown the server
- serverFactory.shutdown();
-
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- // ignore
- }
-
- // verify that the size is just 2 - ie connect then disconnect
- // if the client attempts reconnect and we are not handling current
- // state correctly (ie eventing on duplicate disconnects) then we'll
- // see a disconnect for each Assert.failed connection attempt
- Assert.assertEquals(2, watcher.states.size());
-
- zk.close();
- }
-
- /**
- * Verify access to the negotiated session timeout.
- */
- @Test
- public void testSessionTimeoutAccess() throws Exception {
- // validate typical case - requested == negotiated
- DisconnectableZooKeeper zk = createClient(TICK_TIME * 4);
- Assert.assertEquals(TICK_TIME * 4, zk.getSessionTimeout());
- // make sure tostring works in both cases
- LOG.info(zk.toString());
- zk.close();
- LOG.info(zk.toString());
-
- // validate lower limit
- zk = createClient(TICK_TIME);
- Assert.assertEquals(TICK_TIME * 2, zk.getSessionTimeout());
- LOG.info(zk.toString());
- zk.close();
- LOG.info(zk.toString());
-
- // validate upper limit
- zk = createClient(TICK_TIME * 30);
- Assert.assertEquals(TICK_TIME * 20, zk.getSessionTimeout());
- LOG.info(zk.toString());
- zk.close();
- LOG.info(zk.toString());
- }
-
- private class DupWatcher extends CountdownWatcher {
- public List<WatchedEvent> states = new LinkedList<WatchedEvent>();
- public void process(WatchedEvent event) {
- super.process(event);
- if (event.getType() == EventType.None) {
- states.add(event);
- }
- }
- }
-
- @Test
- public void testMinMaxSessionTimeout() throws Exception {
- // override the defaults
- final int MINSESS = 20000;
- final int MAXSESS = 240000;
- {
- ZooKeeperServer zs = ClientBase.getServer(serverFactory);
- zs.setMinSessionTimeout(MINSESS);
- zs.setMaxSessionTimeout(MAXSESS);
- }
-
- // validate typical case - requested == negotiated
- int timeout = 120000;
- DisconnectableZooKeeper zk = createClient(timeout);
- Assert.assertEquals(timeout, zk.getSessionTimeout());
- // make sure tostring works in both cases
- LOG.info(zk.toString());
- zk.close();
- LOG.info(zk.toString());
-
- // validate lower limit
- zk = createClient(MINSESS/2);
- Assert.assertEquals(MINSESS, zk.getSessionTimeout());
- LOG.info(zk.toString());
- zk.close();
- LOG.info(zk.toString());
-
- // validate upper limit
- zk = createClient(MAXSESS * 2);
- Assert.assertEquals(MAXSESS, zk.getSessionTimeout());
- LOG.info(zk.toString());
- zk.close();
- LOG.info(zk.toString());
- }
-
- @Test
- public void testMaximumCnxnPerIP() throws Exception {
- final int maxClientCnxnsPerIP = 3;
- serverFactory.setMaxClientCnxnsPerHost(maxClientCnxnsPerIP);
- ZooKeeper[] clients = new ZooKeeper[maxClientCnxnsPerIP + 1];
- for (int i = 0; i < clients.length; i++) {
- CountdownWatcher watcher = new CountdownWatcher();
- // wait for 3s
- int timeout = 3000;
- clients[i] = new DisconnectableZooKeeper(HOSTPORT, timeout, watcher);
- boolean result = watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS);
- if (i >= maxClientCnxnsPerIP) {
- Assert.assertFalse(result);
- } else {
- Assert.assertTrue(result);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java
deleted file mode 100644
index 09badae..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java
+++ /dev/null
@@ -1,129 +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.test;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.TestableZooKeeper;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-public class SessionTimeoutTest extends ClientBase {
- protected static final Logger LOG = LoggerFactory.getLogger(SessionTimeoutTest.class);
-
- private TestableZooKeeper zk;
-
- @Before
- public void setUp() throws Exception {
- super.setUp();
- zk = createClient();
- }
-
- @Test
- public void testSessionExpiration() throws InterruptedException,
- KeeperException {
- final CountDownLatch expirationLatch = new CountDownLatch(1);
- Watcher watcher = new Watcher() {
- @Override
- public void process(WatchedEvent event) {
- if ( event.getState() == Event.KeeperState.Expired ) {
- expirationLatch.countDown();
- }
- }
- };
- zk.exists("/foo", watcher);
-
- zk.getTestable().injectSessionExpiration();
- Assert.assertTrue(expirationLatch.await(5, TimeUnit.SECONDS));
-
- boolean gotException = false;
- try {
- zk.exists("/foo", false);
- Assert.fail("Should have thrown a SessionExpiredException");
- } catch (KeeperException.SessionExpiredException e) {
- // correct
- gotException = true;
- }
- Assert.assertTrue(gotException);
- }
-
- /**
- * Make sure ephemerals get cleaned up when session disconnects.
- */
- @Test
- public void testSessionDisconnect() throws KeeperException, InterruptedException, IOException {
- zk.create("/sdisconnect", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- assertNotNull("Ephemeral node has not been created", zk.exists("/sdisconnect", null));
-
- zk.close();
-
- zk = createClient();
- assertNull("Ephemeral node shouldn't exist after client disconnect", zk.exists("/sdisconnect", null));
- }
-
- /**
- * Make sure ephemerals are kept when session restores.
- */
- @Test
- public void testSessionRestore() throws KeeperException, InterruptedException, IOException {
- zk.create("/srestore", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- assertNotNull("Ephemeral node has not been created", zk.exists("/srestore", null));
-
- zk.disconnect();
- zk.close();
-
- zk = createClient();
- assertNotNull("Ephemeral node should be present when session is restored", zk.exists("/srestore", null));
- }
-
- /**
- * Make sure ephemerals are kept when server restarts.
- */
- @Test
- public void testSessionSurviveServerRestart() throws Exception {
- zk.create("/sdeath", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- assertNotNull("Ephemeral node has not been created", zk.exists("/sdeath", null));
-
- zk.disconnect();
- stopServer();
- startServer();
- zk = createClient();
-
- assertNotNull("Ephemeral node should be present when server restarted", zk.exists("/sdeath", null));
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/cb9f303b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java
----------------------------------------------------------------------
diff --git a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java b/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java
deleted file mode 100644
index d8c9bb9..0000000
--- a/zookeeper-common/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java
+++ /dev/null
@@ -1,227 +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.test;
-
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.zookeeper.KeeperException.SessionExpiredException;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.SessionTracker.Session;
-import org.apache.zookeeper.server.SessionTracker.SessionExpirer;
-import org.apache.zookeeper.server.ZooKeeperServerListener;
-import org.apache.zookeeper.server.quorum.LeaderSessionTracker;
-import org.apache.zookeeper.server.quorum.LearnerSessionTracker;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Validate various type of sessions against leader session tracker and learner
- * session tracker
- */
-public class SessionTrackerCheckTest extends ZKTestCase {
-
- protected static final Logger LOG = LoggerFactory
- .getLogger(SessionTrackerCheckTest.class);
- public static final int TICK_TIME = 1000;
- public static final int CONNECTION_TIMEOUT = TICK_TIME * 10;
-
- private ConcurrentHashMap<Long, Integer> sessionsWithTimeouts =
- new ConcurrentHashMap<Long, Integer>();
-
- private class Expirer implements SessionExpirer {
- long sid;
-
- public Expirer(long sid) {
- this.sid = sid;
- }
-
- public void expire(Session session) {
- }
-
- public long getServerId() {
- return sid;
- }
- }
-
- @Before
- public void setUp() throws Exception {
- sessionsWithTimeouts.clear();
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testLearnerSessionTracker() throws Exception {
- Expirer expirer = new Expirer(1);
- // With local session on
- LearnerSessionTracker tracker = new LearnerSessionTracker(expirer,
- sessionsWithTimeouts, TICK_TIME, expirer.sid, true,
- testZKSListener());
-
- // Unknown session
- long sessionId = 0xb100ded;
- try {
- tracker.checkSession(sessionId, null);
- Assert.fail("Unknown session should have failed");
- } catch (SessionExpiredException e) {
- // Get expected exception
- }
-
- // Global session
- sessionsWithTimeouts.put(sessionId, CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Global session should not fail");
- }
-
- // Local session
- sessionId = tracker.createSession(CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Local session should not fail");
- }
-
- // During session upgrade
- sessionsWithTimeouts.put(sessionId, CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Session during upgrade should not fail");
- }
-
- // With local session off
- tracker = new LearnerSessionTracker(expirer, sessionsWithTimeouts,
- TICK_TIME, expirer.sid, false, testZKSListener());
-
- // Should be noop
- sessionId = 0xdeadbeef;
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Should not get any exception");
- }
-
- }
-
- @Test
- public void testLeaderSessionTracker() throws Exception {
- Expirer expirer = new Expirer(2);
- // With local session on
- LeaderSessionTracker tracker = new LeaderSessionTracker(expirer,
- sessionsWithTimeouts, TICK_TIME, expirer.sid, true,
- testZKSListener());
-
- // Local session from other server
- long sessionId = ((expirer.sid + 1) << 56) + 1;
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("local session from other server should not fail");
- }
-
- // Track global session
- tracker.trackSession(sessionId, CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Global session should not fail");
- }
- try {
- tracker.checkGlobalSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Global session should not fail " + e);
- }
-
- // Local session from the leader
- sessionId = tracker.createSession(CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Local session on the leader should not fail");
- }
-
- // During session upgrade
- tracker.trackSession(sessionId, CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Session during upgrade should not fail");
- }
- try {
- tracker.checkGlobalSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Global session should not fail " + e);
- }
-
- // With local session off
- tracker = new LeaderSessionTracker(expirer, sessionsWithTimeouts,
- TICK_TIME, expirer.sid, false, testZKSListener());
-
- // Global session
- sessionId = 0xdeadbeef;
- tracker.trackSession(sessionId, CONNECTION_TIMEOUT);
- try {
- tracker.checkSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Global session should not fail");
- }
- try {
- tracker.checkGlobalSession(sessionId, null);
- } catch (Exception e) {
- Assert.fail("Global session should not fail");
- }
-
- // Local session from other server
- sessionId = ((expirer.sid + 1) << 56) + 2;
- try {
- tracker.checkSession(sessionId, null);
- Assert.fail("local session from other server should fail");
- } catch (SessionExpiredException e) {
- // Got expected exception
- }
-
- // Local session from the leader
- sessionId = ((expirer.sid) << 56) + 2;
- try {
- tracker.checkSession(sessionId, null);
- Assert.fail("local session from the leader should fail");
- } catch (SessionExpiredException e) {
- // Got expected exception
- }
-
- }
-
- ZooKeeperServerListener testZKSListener() {
- return new ZooKeeperServerListener() {
-
- @Override
- public void notifyStopping(String errMsg, int exitCode) {
-
- }
- };
- }
-}