@Override public void setUp() throws Exception { String hp = hostPort; hostPort = hostPort + "/chrootasynctest"; super.setUp(); LOG.info("Creating client " + getTestName()); ZooKeeper zk = createClient(hp); try { zk.create("/chrootasynctest", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } finally { zk.close(); } }
@Ignore("DLR is broken by HBASE-12751") @Test(timeout=60000) public void testGetPreviousRecoveryMode() throws Exception { LOG.info("testGetPreviousRecoveryMode"); SplitLogCounters.resetCounters(); // Not actually enabling DLR for the cluster, just for the ZkCoordinatedStateManager to use. // The test is just manipulating ZK manually anyways. conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, true); zkw.getRecoverableZooKeeper().create(ZKSplitLog.getEncodedNodeName(zkw, "testRecovery"), new SplitLogTask.Unassigned( ServerName.valueOf("mgr,1,1"), RecoveryMode.LOG_SPLITTING).toByteArray(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); slm = new SplitLogManager(ds, conf, stopper, master, DUMMY_MASTER); LOG.info("Mode1=" + slm.getRecoveryMode()); assertTrue(slm.isLogSplitting()); zkw.getRecoverableZooKeeper().delete(ZKSplitLog.getEncodedNodeName(zkw, "testRecovery"), -1); LOG.info("Mode2=" + slm.getRecoveryMode()); slm.setRecoveryMode(false); LOG.info("Mode3=" + slm.getRecoveryMode()); assertTrue("Mode4=" + slm.getRecoveryMode(), slm.isLogReplaying()); }
/** * Test to verify that server is able to start with invalid credentials if * the configuration is set to quorum.auth.serverRequireSasl=false. * Quorum will talk each other even if the authentication is not succeeded */ @Test(timeout = 30000) public void testSaslNotRequiredWithInvalidCredentials() throws Exception { Map<String, String> authConfigs = new HashMap<String, String>(); authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearnerInvalid"); authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "false"); authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "false"); String connectStr = startQuorum(3, authConfigs, 3, false); CountdownWatcher watcher = new CountdownWatcher(); zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher); watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT); for (int i = 0; i < 10; i++) { zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } }
public void run() { byte b[] = new byte[256]; try { for (; current < count; current++) { // Simulate a bit of network latency... Thread.sleep(HAMMERTHREAD_LATENCY); zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } catch (Throwable t) { LOG.error("Client create operation Assert.failed", t); } finally { try { zk.close(); } catch (InterruptedException e) { LOG.warn("Unexpected", e); } } }
@Test public void testNoWatchesTriggeredForFailedMultiRequest() throws InterruptedException, KeeperException { HasTriggeredWatcher watcher = new HasTriggeredWatcher(); zk.getChildren("/", watcher); try { multi(zk, Arrays.asList( Op.create("/t", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.delete("/nonexisting", -1) )); fail("expected previous multi op to fail!"); } catch (KeeperException.NoNodeException e) { // expected } SyncCallback cb = new SyncCallback(); zk.sync("/", cb, null); // by waiting for the callback we're assured that the event queue is flushed cb.done.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); assertEquals(1, watcher.triggered.getCount()); }
@Test public void testChRootSetData() throws Exception { // creating the subtree for chRoot clients. String chRoot = createNameSpace(); // setData using chRoot client. zk_chroot = createClient(this.hostPort + chRoot); String[] names = {"/multi0", "/multi1", "/multi2"}; List<Op> ops = new ArrayList<Op>(); for (int i = 0; i < names.length; i++) { ops.add(Op.create(names[i], new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); ops.add(Op.setData(names[i], names[i].getBytes(), 0)); } multi(zk_chroot, ops) ; for (int i = 0; i < names.length; i++) { Assert.assertArrayEquals("zNode data not matching", names[i] .getBytes(), zk_chroot.getData(names[i], false, null)); } }
public void run() { byte b[] = new byte[256]; try { for (; current < count; current++) { ZooKeeper zk = parent.createClient(); try { zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } finally { try { zk.close(); } catch (InterruptedException e) { LOG.warn("Unexpected", e); } } } } catch (Throwable t) { LOG.error("Client create operation Assert.failed", t); } }
/** * signal the workers that a task was resubmitted by creating the RESCAN node. */ private void rescan(long retries) { // The RESCAN node will be deleted almost immediately by the // SplitLogManager as soon as it is created because it is being // created in the DONE state. This behavior prevents a buildup // of RESCAN nodes. But there is also a chance that a SplitLogWorker // might miss the watch-trigger that creation of RESCAN node provides. // Since the TimeoutMonitor will keep resubmitting UNASSIGNED tasks // therefore this behavior is safe. SplitLogTask slt = new SplitLogTask.Done(this.details.getServerName(), getRecoveryMode()); this.watcher .getRecoverableZooKeeper() .getZooKeeper() .create(ZKSplitLog.getRescanNode(watcher), slt.toByteArray(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new CreateRescanAsyncCallback(), Long.valueOf(retries)); }
/** * ZOOKEEPER-2052: * This test checks that if a multi operation aborted, and during the multi there is side effect * that changed outstandingChangesForPath, after aborted the side effect should be removed and * everything should be restored correctly. */ @Test public void testMultiRollbackNoLastChange() throws Exception { zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0); zks.getZKDatabase().dataTree.createNode("/foo/bar", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0); Assert.assertNull(zks.outstandingChangesForPath.get("/foo")); // multi record: // set "/foo" => succeed, leave a outstanding change // delete "/foo" => fail, roll back change process(Arrays.asList( Op.setData("/foo", new byte[0], -1), Op.delete("/foo", -1))); // aborting multi shouldn't leave any record. Assert.assertNull(zks.outstandingChangesForPath.get("/foo")); }
/** * Test verifies deletion of NodeDataChanged watches */ @Test(timeout = 30000) public void testRemoveNodeDataChangedWatches() throws Exception { LOG.info("Adding data watcher using getData()"); List<EventType> expectedEvents = new ArrayList<Watcher.Event.EventType>(); expectedEvents.add(EventType.DataWatchRemoved); MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 1); zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zk.getData("/testnode1", myWatcher, null); String cmdstring = "removewatches /testnode1 -d"; LOG.info("Remove watchers using shell command : {}", cmdstring); zkMain.cl.parseCommand(cmdstring); Assert.assertTrue("Removewatches cmd fails to remove data watches", zkMain.processZKCmd(zkMain.cl)); LOG.info("Waiting for the DataWatchRemoved event"); myWatcher.matches(); // verifying that other path data watches are removed Assert.assertEquals( "Data watches are not removed : " + zk.getDataWatches(), 0, zk .getDataWatches().size()); }
@Test public void testQuitElectionRemovesBreadcrumbNode() throws Exception { mockNoPriorActive(); elector.joinElection(data); elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME); // Writes its own active info Mockito.verify(mockZK, Mockito.times(1)).create( Mockito.eq(ZK_BREADCRUMB_NAME), Mockito.eq(data), Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT)); mockPriorActive(data); elector.quitElection(false); // Deletes its own active data Mockito.verify(mockZK, Mockito.times(1)).delete( Mockito.eq(ZK_BREADCRUMB_NAME), Mockito.eq(0)); }
@Test public void testLargeNodeData() throws Exception { ZooKeeper zk= null; String queue_handle = "/large"; try { zk = createClient(); zk.create(queue_handle, new byte[500000], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } finally { if (zk != null) { zk.close(); } } }
@Test public void testNestedCreate() throws Exception { multi(zk, Arrays.asList( /* Create */ Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create("/multi/a", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create("/multi/a/1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), /* Delete */ Op.delete("/multi/a/1", 0), Op.delete("/multi/a", 0), Op.delete("/multi", 0) )); //Verify tree deleted Assert.assertNull(zk.exists("/multi/a/1", null)); Assert.assertNull(zk.exists("/multi/a", null)); Assert.assertNull(zk.exists("/multi", null)); }
/** * verify that if create znode results in nodeexists and that znode is deleted * before exists() watch is set then the return of the exists() method results * in attempt to re-create the znode and become active */ @Test public void testCreateNodeResultRetryNoNode() { elector.joinElection(data); elector.processResult(Code.CONNECTIONLOSS.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME); elector.processResult(Code.CONNECTIONLOSS.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME); elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME); verifyExistCall(1); elector.processResult(Code.NONODE.intValue(), ZK_LOCK_NAME, mockZK, (Stat) null); Mockito.verify(mockApp, Mockito.times(1)).enterNeutralMode(); Mockito.verify(mockZK, Mockito.times(4)).create(ZK_LOCK_NAME, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK); }
public boolean createNode(String parent, String nodeName) { if (connected) { try { String[] nodeElements = nodeName.split("/"); for (String nodeElement : nodeElements) { String node = parent + "/" + nodeElement; Stat s = zooKeeper.exists(node, false); if (s == null) { zooKeeper.create(node, this.encryptionManager .encryptData(null), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); parent = node; } } return true; } catch (Exception e) { LoggerFactory.getLogger().error( "Error occurred creating node: " + parent + "/" + nodeName, e); } } return false; }
@Test public void testBasic() throws IOException, KeeperException, InterruptedException { String name = "/foo"; zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Stat stat; stat = newStat(); zk.getData(name, false, stat); Assert.assertEquals(stat.getCzxid(), stat.getMzxid()); Assert.assertEquals(stat.getCzxid(), stat.getPzxid()); Assert.assertEquals(stat.getCtime(), stat.getMtime()); Assert.assertEquals(0, stat.getCversion()); Assert.assertEquals(0, stat.getVersion()); Assert.assertEquals(0, stat.getAversion()); Assert.assertEquals(0, stat.getEphemeralOwner()); Assert.assertEquals(name.length(), stat.getDataLength()); Assert.assertEquals(0, stat.getNumChildren()); }
private void create_get_stat_test() throws IOException, InterruptedException, KeeperException { checkRoot(); ZooKeeper zk = new ZooKeeper(hostPort, 10000, this); String parentName = testDirOnZK; String nodeName = parentName + "/create_with_stat_tmp"; deleteNodeIfExists(zk, nodeName); deleteNodeIfExists(zk, nodeName + "_2"); Stat stat = new Stat(); zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat); Assert.assertNotNull(stat); Assert.assertTrue(stat.getCzxid() > 0); Assert.assertTrue(stat.getCtime() > 0); Stat stat2 = new Stat(); zk.create(nodeName + "_2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat2); Assert.assertNotNull(stat2); Assert.assertTrue(stat2.getCzxid() > stat.getCzxid()); Assert.assertTrue(stat2.getCtime() > stat.getCtime()); deleteNodeIfExists(zk, nodeName); deleteNodeIfExists(zk, nodeName + "_2"); zk.close(); }
@Test (timeout=180000) public void testOrphanTaskAcquisition() throws Exception { LOG.info("TestOrphanTaskAcquisition"); String tasknode = ZKSplitLog.getEncodedNodeName(zkw, "orphan/test/slash"); SplitLogTask slt = new SplitLogTask.Owned(DUMMY_MASTER, this.mode); zkw.getRecoverableZooKeeper().create(tasknode, slt.toByteArray(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); slm = new SplitLogManager(ds, conf, stopper, master, DUMMY_MASTER); waitForCounter(tot_mgr_orphan_task_acquired, 0, 1, to/2); Task task = slm.findOrCreateOrphanTask(tasknode); assertTrue(task.isOrphan()); waitForCounter(tot_mgr_heartbeat, 0, 1, to/2); assertFalse(task.isUnassigned()); long curt = System.currentTimeMillis(); assertTrue((task.last_update <= curt) && (task.last_update > (curt - 1000))); LOG.info("waiting for manager to resubmit the orphan task"); waitForCounter(tot_mgr_resubmit, 0, 1, to + to/2); assertTrue(task.isUnassigned()); waitForCounter(tot_mgr_rescan, 0, 1, to + to/2); }
public void verifyMultiSequential_NoSideEffect() throws Exception{ StringCB scb = new StringCB(zk); scb.verifyCreate(); String path = scb.path + "-"; String seqPath = path + "0000000002"; zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); Assert.assertNotNull(zk.exists(path + "0000000001", false)); List<Op> ops = Arrays.asList( Op.create(path , new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL), Op.delete("/nonexist", -1)); zk.multi(ops, this, null); latch_await(); Assert.assertNull(zk.exists(seqPath, false)); zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); Assert.assertNotNull(zk.exists(seqPath, false)); }
/** * Test verifies the multi.create with invalid createModeFlag */ @Test(timeout = 90000) public void testInvalidCreateModeFlag() throws Exception { List<Integer> expectedResultCodes = new ArrayList<Integer>(); expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY .intValue()); expectedResultCodes.add(KeeperException.Code.BADARGUMENTS.intValue()); expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY .intValue()); int createModeFlag = 6789; List<Op> opList = Arrays.asList(Op.create("/multi0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create("/multi1", new byte[0], Ids.OPEN_ACL_UNSAFE, createModeFlag), Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); String expectedErr = KeeperException.Code.BADARGUMENTS.name(); multiHavingErrors(zk, opList, expectedResultCodes, expectedErr); }
@Test public void testChRootCreateDelete() throws Exception { // creating the subtree for chRoot clients. String chRoot = createNameSpace(); // Creating child using chRoot client. zk_chroot = createClient(this.hostPort + chRoot); Op createChild = Op.create("/myid", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); multi(zk_chroot, Arrays.asList(createChild)); Assert.assertNotNull("zNode is not created under chroot:" + chRoot, zk .exists(chRoot + "/myid", false)); Assert.assertNotNull("zNode is not created under chroot:" + chRoot, zk_chroot.exists("/myid", false)); Assert.assertNull("zNode is created directly under '/', ignored configured chroot", zk.exists("/myid", false)); // Deleting child using chRoot client. Op deleteChild = Op.delete("/myid", 0); multi(zk_chroot, Arrays.asList(deleteChild)); Assert.assertNull("zNode exists under chroot:" + chRoot, zk.exists( chRoot + "/myid", false)); Assert.assertNull("zNode exists under chroot:" + chRoot, zk_chroot .exists("/myid", false)); }
@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(); } }
@Test public void testDeleteUpdateConflict() throws Exception { /* Delete of a node folowed by an update of the (now) deleted node */ try { multi(zk, Arrays.asList( Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.delete("/multi", 0), Op.setData("/multi", "Y".getBytes(), 0) )); Assert.fail("/multi should have been deleted so setData should have failed"); } catch (KeeperException e) { /* PASS */ } // '/multi' should never have been created as entire op should fail Assert.assertNull(zk.exists("/multi", null)) ; }
@Test public void testChRootCheck() throws Exception { // creating the subtree for chRoot clients. String chRoot = createNameSpace(); // checking the child version using chRoot client. zk_chroot = createClient(this.hostPort + chRoot); String[] names = {"/multi0", "/multi1", "/multi2"}; List<Op> ops = new ArrayList<Op>(); for (int i = 0; i < names.length; i++) { zk.create(chRoot + names[i], new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } for (int i = 0; i < names.length; i++) { ops.add(Op.check(names[i], 0)); } multi(zk_chroot, ops) ; }
/** * Test verifies null watcher */ @Test(timeout = 30000) public void testNullWatcherReference() throws Exception { zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); try { if (useAsync) { zk1.removeWatches("/node1", null, WatcherType.Data, false, null, null); } else { zk1.removeWatches("/node1", null, WatcherType.Data, false); } Assert.fail("Must throw IllegalArgumentException as watcher is null!"); } catch (IllegalArgumentException iae) { // expected } }
private void initZK() throws HadoopIllegalArgumentException, IOException, KeeperException { zkQuorum = conf.get(ZK_QUORUM_KEY); int zkTimeout = conf.getInt(ZK_SESSION_TIMEOUT_KEY, ZK_SESSION_TIMEOUT_DEFAULT); // Parse ACLs from configuration. String zkAclConf = conf.get(ZK_ACL_KEY, ZK_ACL_DEFAULT); zkAclConf = ZKUtil.resolveConfIndirection(zkAclConf); List<ACL> zkAcls = ZKUtil.parseACLs(zkAclConf); if (zkAcls.isEmpty()) { zkAcls = Ids.CREATOR_ALL_ACL; } // Parse authentication from configuration. String zkAuthConf = conf.get(ZK_AUTH_KEY); zkAuthConf = ZKUtil.resolveConfIndirection(zkAuthConf); List<ZKAuthInfo> zkAuths; if (zkAuthConf != null) { zkAuths = ZKUtil.parseAuth(zkAuthConf); } else { zkAuths = Collections.emptyList(); } // Sanity check configuration. Preconditions.checkArgument(zkQuorum != null, "Missing required configuration '%s' for ZooKeeper quorum", ZK_QUORUM_KEY); Preconditions.checkArgument(zkTimeout > 0, "Invalid ZK session timeout %s", zkTimeout); int maxRetryNum = conf.getInt( CommonConfigurationKeys.HA_FC_ELECTOR_ZK_OP_RETRIES_KEY, CommonConfigurationKeys.HA_FC_ELECTOR_ZK_OP_RETRIES_DEFAULT); elector = new ActiveStandbyElector(zkQuorum, zkTimeout, getParentZnode(), zkAcls, zkAuths, new ElectorCallbacks(), maxRetryNum); }
/** * 创建父节点以及节点在zookeeper上/对存在的节点值进行更新 * * @param zkClient * zk客户端对象 * @param znodePath * znode路径 * @param nodeValue * znode存放值 * @throws Exception * 往上层抛异常 */ public static void createOrUpdateZnode(Client zkClient, String znodePath, String nodeValue) throws Exception { Stat stat = null; // 往zk塞数据 stat = zkClient.getZooKeeper().exists(znodePath, false); if (null != stat) { // 更新数据 zkClient.getZooKeeper().setData(znodePath, nodeValue.getBytes(), stat.getVersion()); } else { // 创造数据 if (znodePath.indexOf(PathVarConst.ROOTCONF_PATH) != -1) { // 遍历创造父节点,父节点存的值为自己的全路径 String createNodePaths = znodePath.substring( znodePath.indexOf(PathVarConst.ROOTCONF_PATH) + PathVarConst.ROOTCONF_PATH.length() + 1); int index = createNodePaths.indexOf("/"); String nodePath = PathVarConst.ROOTCONF_PATH; while (index != -1) { nodePath += "/" + createNodePaths.substring(0, index); createNodePaths = createNodePaths.substring(index + 1); stat = zkClient.getZooKeeper().exists(nodePath, false); if (stat == null) { zkClient.getZooKeeper().create(nodePath, nodePath.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } index = createNodePaths.indexOf("/"); } // 最后创建目的节点 stat = zkClient.getZooKeeper().exists(nodePath + "/" + createNodePaths, false); if (stat == null) { zkClient.getZooKeeper().create(nodePath + "/" + createNodePaths, nodeValue.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } else { throw new RuntimeException(znodePath + "-->节点路径不符合zookeeper约定"); } } }
private void utestPrep(int port) throws IOException, InterruptedException, KeeperException { ZooKeeper zk = new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this); for (int i = 0; i < 10000; i++) { zk.create("/" + i, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } zk.close(); }
@Test public void testCreateDelete() throws Exception { multi(zk, Arrays.asList( Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.delete("/multi", 0) )); // '/multi' should have been deleted Assert.assertNull(zk.exists("/multi", null)); }
@Test public void testUpdateConflict() throws Exception { Assert.assertNull(zk.exists("/multi", null)); try { multi(zk, Arrays.asList( Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.setData("/multi", "X".getBytes(), 0), Op.setData("/multi", "Y".getBytes(), 0) )); Assert.fail("Should have thrown a KeeperException for invalid version"); } catch (KeeperException e) { //PASS LOG.error("STACKTRACE: " + e); } Assert.assertNull(zk.exists("/multi", null)); //Updating version solves conflict -- order matters multi(zk, Arrays.asList( Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.setData("/multi", "X".getBytes(), 0), Op.setData("/multi", "Y".getBytes(), 1) )); Assert.assertArrayEquals(zk.getData("/multi", false, null), "Y".getBytes()); }
/** * Test that ensureBaseNode() recursively creates the specified dir */ @Test public void testEnsureBaseNode() throws Exception { elector.ensureParentZNode(); StringBuilder prefix = new StringBuilder(); for (String part : ZK_PARENT_NAME.split("/")) { if (part.isEmpty()) continue; prefix.append("/").append(part); if (!"/".equals(prefix.toString())) { Mockito.verify(mockZK).create( Mockito.eq(prefix.toString()), Mockito.<byte[]>any(), Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT)); } } }
/** * verify the zookeeper connection establishment */ @Test public void testWithoutZKServer() throws Exception { try { new ActiveStandbyElector("127.0.0.1", 2000, ZK_PARENT_NAME, Ids.OPEN_ACL_UNSAFE, Collections.<ZKAuthInfo> emptyList(), mockApp, CommonConfigurationKeys.HA_FC_ELECTOR_ZK_OP_RETRIES_DEFAULT); Assert.fail("Did not throw zookeeper connection loss exceptions!"); } catch (KeeperException ke) { GenericTestUtils.assertExceptionContains( "ConnectionLoss", ke); } }
/** * joinElection(..) should happen only after SERVICE_HEALTHY. */ @Test public void testBecomeActiveBeforeServiceHealthy() throws Exception { mockNoPriorActive(); WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class); Mockito.when(mockEvent.getType()).thenReturn(Event.EventType.None); // session expired should enter safe mode // But for first time, before the SERVICE_HEALTY i.e. appData is set, // should not enter the election. Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.Expired); elector.processWatchEvent(mockZK, mockEvent); // joinElection should not be called. Mockito.verify(mockZK, Mockito.times(0)).create(ZK_LOCK_NAME, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK); }
/** * Test verifies removal of multiple child watchers when there is server * connection */ @Test(timeout = 90000) public void testMultipleChildWatchers() throws IOException, InterruptedException, KeeperException { zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); MyWatcher w1 = new MyWatcher("/node1", 1); LOG.info("Adding child watcher {} on path {}", new Object[] { w1, "/node1" }); zk2.getChildren("/node1", w1); MyWatcher w2 = new MyWatcher("/node1", 1); LOG.info("Adding child watcher {} on path {}", new Object[] { w2, "/node1" }); zk2.getChildren("/node1", w2); removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK); Assert.assertTrue("Didn't remove child watcher", w2.matches()); Assert.assertEquals("Didn't find child watcher", 1, zk2 .getChildWatches().size()); removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK); Assert.assertTrue("Didn't remove child watcher", w1.matches()); // create child to see NodeChildren notification zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); // waiting for child watchers to be notified int count = 30; while (count > 0) { if (w1.getEventsAfterWatchRemoval().size() > 0) { break; } count--; Thread.sleep(100); } // watcher2 List<EventType> events = w2.getEventsAfterWatchRemoval(); Assert.assertEquals("Shouldn't get NodeChildrenChanged event", 0, events.size()); }