List of usage examples for org.apache.zookeeper ZooKeeper getSessionId
public long getSessionId()
From source file:co.cask.tephra.distributed.ThriftTransactionServerTest.java
License:Apache License
private void expireZkSession(ZKClientService zkClientService) throws Exception { ZooKeeper zooKeeper = zkClientService.getZooKeeperSupplier().get(); final SettableFuture<?> connectFuture = SettableFuture.create(); Watcher watcher = new Watcher() { @Override/* ww w. java 2 s .c o m*/ public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { connectFuture.set(null); } } }; // Create another Zookeeper session with the same sessionId so that the original one expires. final ZooKeeper dupZookeeper = new ZooKeeper(zkClientService.getConnectString(), zooKeeper.getSessionTimeout(), watcher, zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); connectFuture.get(30, TimeUnit.SECONDS); Assert.assertEquals("Failed to re-create current session", dupZookeeper.getState(), ZooKeeper.States.CONNECTED); dupZookeeper.close(); }
From source file:co.cask.tephra.zookeeper.TephraZKClientService.java
License:Apache License
@Override public Long getSessionId() { ZooKeeper zk = zooKeeper.get(); return zk == null ? null : zk.getSessionId(); }
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.ZooKeeperClientTest.java
License:Apache License
@Test public void testClient() { ZkClientx zk = ZooKeeperClient.getInstance(); // ?zk??/* www .j a v a 2 s .c o m*/ final ZooKeeper zkp = ((ZooKeeperx) zk.getConnection()).getZookeeper(); ClientCnxn cnxn = (ClientCnxn) ReflectionUtils.getField(clientCnxnField, zkp); HostProvider hostProvider = (HostProvider) ReflectionUtils.getField(hostProviderField, cnxn); List<InetSocketAddress> serverAddrs = (List<InetSocketAddress>) ReflectionUtils .getField(serverAddressesField, hostProvider); want.number(serverAddrs.size()).isEqualTo(3); String s1 = serverAddrs.get(0).getAddress().getHostAddress() + ":" + serverAddrs.get(0).getPort(); want.string(s1).isEqualTo(cluster1); Stat stat = new Stat(); try { zkp.getChildren("/otter/channel/304/388", false, stat); System.out.println(stat.getCversion()); } catch (KeeperException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } // session timeout final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { try { zkp.getChildren("/", false); } catch (KeeperException e1) { want.fail(); } catch (InterruptedException e1) { want.fail(); } int sessionTimeout = zkp.getSessionTimeout(); long sessionId = zkp.getSessionId(); byte[] passwd = zkp.getSessionPasswd(); try { ZooKeeper newZk = new ZooKeeper(cluster1, sessionTimeout, new Watcher() { public void process(WatchedEvent event) { // do nothing } }, sessionId, passwd); // ?sessionIdclose??SESSION_EXPIRED newZk.close(); } catch (IOException e) { want.fail(); } catch (InterruptedException e) { want.fail(); } latch.countDown(); } }.start(); try { latch.await(); } catch (InterruptedException e) { want.fail(); } zk.getChildren("/"); }
From source file:com.bigdata.zookeeper.AbstractZooTestCase.java
License:Open Source License
/** * Return a new {@link ZooKeeper} instance that is connected to the same * zookeeper ensemble as the given instance and is using the same session * but is nevertheless a distinct instance. * <p>/*from w w w. j a va2 s . c o m*/ * Note: This is used by some unit tests to force the given * {@link ZooKeeper} to report a {@link SessionExpiredException} by closing * the returned instance. * * @param zookeeper * A zookeeper instance. * * @return A distinct instance associated with the same session. * * @throws IOException * @throws InterruptedException */ protected ZooKeeper getDistinctZooKeeperForSameSession(final ZooKeeper zookeeper1) throws IOException, InterruptedException { final ZooKeeper zookeeper2 = new ZooKeeper(zookeeperAccessor.hosts, zookeeperAccessor.sessionTimeout, new Watcher() { public void process(WatchedEvent e) { } }, zookeeper1.getSessionId(), zookeeper1.getSessionPasswd()); /* * Wait until this instance is connected. */ final long timeout = TimeUnit.MILLISECONDS.toNanos(1000/* ms */); final long begin = System.nanoTime(); while (zookeeper2.getState() != ZooKeeper.States.CONNECTED && zookeeper2.getState().isAlive()) { final long elapsed = System.nanoTime() - begin; if (elapsed > timeout) { fail("ZooKeeper session did not connect? elapsed=" + TimeUnit.NANOSECONDS.toMillis(elapsed)); } if (log.isInfoEnabled()) { log.info("Awaiting connected."); } Thread.sleep(100/* ms */); } if (!zookeeper2.getState().isAlive()) { fail("Zookeeper died?"); } if (log.isInfoEnabled()) log.info("Zookeeper connected."); return zookeeper2; }
From source file:com.bigdata.zookeeper.TestZookeeperSessionSemantics.java
License:Open Source License
public void test_handleExpiredSession() throws InterruptedException, KeeperException, IOException { final String hosts = "localhost:" + clientPort; final Lock lock = new ReentrantLock(); final Condition expireCond = lock.newCondition(); final Condition connectCond = lock.newCondition(); final Condition disconnectCond = lock.newCondition(); final AtomicBoolean didExpire = new AtomicBoolean(false); final AtomicBoolean didDisconnect = new AtomicBoolean(false); /*//from ww w . j a v a2 s . co m * Start an instance and run until it gets an assigned sessionId. */ { final ZooKeeper zk1a = new ZooKeeper(hosts, requestedSessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { log.warn(event); } }); int i = 0; while (i < 10) { boolean done = false; if (zk1a.getState() == ZooKeeper.States.CONNECTED) { done = true; } log.info("zk.getState()=" + zk1a.getState() + ", zk.getSessionId()=" + zk1a.getSessionId()); if (done) break; Thread.sleep(500); i++; } if (zk1a.getState() != ZooKeeper.States.CONNECTED) { fail("Did not connect."); } zk1a.close(); } final ZooKeeper zk1 = new ZooKeeper(hosts, requestedSessionTimeout, new Watcher() { /** * Note: The default watcher will not receive any events * after a session expire. A {@link Zookeeper#close()} * causes an immediate session expire. Thus, no events * (include the session expire) will be received after a * close(). */ @Override public void process(final WatchedEvent event) { log.warn(event); switch (event.getState()) { case AuthFailed: break; case Disconnected: lock.lock(); try { didDisconnect.set(true); disconnectCond.signalAll(); } finally { lock.unlock(); } break; case Expired: lock.lock(); try { didExpire.set(true); expireCond.signalAll(); } finally { lock.unlock(); } break; // case ConnectedReadOnly: // not in 3.3.3 // break; // case NoSyncConnected: // not in 3.3.3 // break; // case SaslAuthenticated: // not in 3.3.3 // break; case SyncConnected: lock.lock(); try { connectCond.signalAll(); } finally { lock.unlock(); } break; case Unknown: break; } } }); /* * Note: You can not obtain the negotiated session timeout until the * zookeeper client has connected to a zookeeper service (or rather, * it will return ZERO until it is connected). */ final int negotiatedSessionTimeout; lock.lock(); try { log.info("Waiting zk connected."); connectCond.await(10, TimeUnit.SECONDS); negotiatedSessionTimeout = zk1.getSessionTimeout(); if (log.isInfoEnabled()) log.info("Negotiated sessionTimeout=" + negotiatedSessionTimeout); assertNotSame(0, negotiatedSessionTimeout); assertTrue(negotiatedSessionTimeout > 0); } finally { lock.unlock(); } assertTrue(zk1.getState().isAlive()); assertFalse(didDisconnect.get()); assertFalse(didExpire.get()); // clear out test znodes. destroyZNodes(zk1, "/test"); // ensure root /test znode exists. try { zk1.create("/test", new byte[] {}, acl, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException ex) { log.warn("Ignoring: " + ex); } // look at that znode, establishing a watcher. zk1.getData("/test", true/* watch */, null/* stat */); // update the znode's data. zk1.setData("/test", new byte[] { 1 }, -1/* version */); // create an ephemeral sequential znode that is a child of /test. final String foozpath = zk1.create("/test/foo", new byte[] {}, acl, CreateMode.EPHEMERAL_SEQUENTIAL); // create a 2nd ephemeral sequential znode that is a child of /test. final String foozpath2 = zk1.create("/test/foo", new byte[] {}, acl, CreateMode.EPHEMERAL_SEQUENTIAL); /* * Look at that znode, establishing a watcher. * * Note: We appear to see node deleted events for the ephemeral znodes * if the client connection is closed, but the state is still reported * as SyncConnected rather than SessionExpired. * * Note: If we do not establish a watcher for an ephemeral znode, then * we DO NOT see an node deleted event when the client is closed! */ zk1.getData(foozpath, true/* watch */, null/* stat */); // zk1.getData(foozpath2, true/* watch */, null/* stat */); //// close the existing instance. // log.info("Closing ZK client"); // zk1.close(); // log.fatal("killing local zookeeper service."); // killZKServer(); // Thread.sleep(5000); // fail("done"); if (false) { log.info("Spin loop awaiting !isAlive() for client."); final long begin = System.currentTimeMillis(); while (zk1.getState().isAlive()) { log.info("zk.getState()=" + zk1.getState() + ", zk.getSessionId()=" + zk1.getSessionId()); final long elapsed = System.currentTimeMillis() - begin; if (elapsed > 60000 * 2) fail("Client still isAlive()."); Thread.sleep(1000); } log.info("Continuing"); } if (true) { log.error("KILL ZOOKEEPER."); Thread.sleep(5000); log.info("Spin loop on ephemeral znode getData() for client."); while (true) { try { zk1.getData(foozpath, true/* watch */, null/* stat */); } catch (KeeperException ex) { log.error(ex, ex); Thread.sleep(1000); continue; } log.info("zk.getState()=" + zk1.getState() + ", zk.getSessionId()=" + zk1.getSessionId()); break; // final long elapsed = System.currentTimeMillis() - begin; // if (elapsed > 60000 * 2) // fail("Client still isAlive()."); // Thread.sleep(1000); } log.info("Continuing"); final byte[] a = zk1.getData(foozpath, true/* watch */, null/* stat */); assertTrue("Expected " + Arrays.toString(new byte[] { 1 }) + ", not " + Arrays.toString(a), BytesUtil.bytesEqual(new byte[] { 1 }, a)); } // // The disconnect event should be immediate. // lock.lock(); // try { // disconnectCond.await(100, TimeUnit.MILLISECONDS); // } finally { // lock.unlock(); // } // // assertTrue(didDisconnect.get()); assertFalse(didDisconnect.get()); assertFalse(didExpire.get()); assertFalse(zk1.getState().isAlive()); /* * Wait up to a little more than the negotiated session timeout for the * session to be expired. */ lock.lock(); try { // Attempt to get the znode again. new Thread(new Runnable() { public void run() { try { final byte[] tmp = zk1.getData("/test", true/* watch */, null/* stat */); } catch (KeeperException e) { log.error(e, e); } catch (InterruptedException e) { log.error(e, e); } } }).start(); expireCond.await(negotiatedSessionTimeout + 10000, TimeUnit.MILLISECONDS); /* * Note: No events are ever delivered to the watcher with * KeeperStates:=SessionExpired. This appears to be a design * decision. */ assertFalse(didExpire.get()); } finally { lock.unlock(); } /* * Now obtain a new session. */ { log.warn("Starting new ZK connection"); final ZooKeeper zk2 = new ZooKeeper(hosts, requestedSessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { log.warn(event); } }); assertTrue(zk2.getState().isAlive()); } }
From source file:com.continuuity.weave.internal.zookeeper.KillZKSession.java
License:Apache License
/** * Kills a Zookeeper client to simulate failure scenarious during testing. * Callee will provide the amount of time to wait before it's considered failure * to kill a client.// ww w .ja v a2 s . com * * @param client that needs to be killed. * @param connectionString of Quorum * @param maxMs time in millisecond specifying the max time to kill a client. * @throws IOException When there is IO error * @throws InterruptedException When call has been interrupted. */ public static void kill(ZooKeeper client, String connectionString, int maxMs) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zk = new ZooKeeper(connectionString, maxMs, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { latch.countDown(); } } }, client.getSessionId(), client.getSessionPasswd()); try { Preconditions.checkState(latch.await(maxMs, TimeUnit.MILLISECONDS), "Fail to kill ZK connection."); } finally { zk.close(); } }
From source file:com.jxt.web.cluster.zookeeper.ZookeeperClient.java
License:Apache License
public void reconnectWhenSessionExpired() { if (!stateContext.isStarted()) { logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed."); return;//ww w. j a v a 2 s .c o m } ZooKeeper zookeeper = this.zookeeper; if (zookeeper.getState().isConnected()) { logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: session(0x{}) is connected.", Long.toHexString(zookeeper.getSessionId())); return; } logger.warn("Execute ZookeeperClient.reconnectWhenSessionExpired()(Expired session:0x{}).", Long.toHexString(zookeeper.getSessionId())); try { zookeeper.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ZooKeeper newZookeeper = createNewZookeeper(); if (newZookeeper == null) { logger.warn("Failed to create new Zookeeper instance. It will be retry AFTER {}ms.", reconnectDelayWhenSessionExpired); timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } reconnectWhenSessionExpired(); } }, reconnectDelayWhenSessionExpired, TimeUnit.MILLISECONDS); } else { this.zookeeper = newZookeeper; } }
From source file:com.linecorp.armeria.client.endpoint.zookeeper.ZooKeeperEndpointGroupTest.java
License:Apache License
@Test public void testConnectionRecovery() throws Exception { ZooKeeper zkHandler1 = zkEndpointGroup.zkFuture().get(); CountDownLatch latch = new CountDownLatch(1); ZooKeeper zkHandler2;/*www. ja va 2s . c o m*/ //create a new handler with the same sessionId and password zkHandler2 = new ZooKeeper(zkInstance.connectString().get(), sessionTimeout, event -> { if (event.getState() == KeeperState.SyncConnected) { latch.countDown(); } }, zkHandler1.getSessionId(), zkHandler1.getSessionPasswd()); latch.await(); //once connected, close the new handler to cause the original handler session expire zkHandler2.close(); for (KeeperState state : expectedStates) { assertEquals(state, zkEndpointGroup.stateQueue().take()); } }
From source file:com.linecorp.armeria.client.zookeeper.EndpointGroupTest.java
License:Apache License
@Test public void testConnectionRecovery() throws Exception { ZooKeeper zkHandler1 = endpointGroup.underlyingClient(); CountDownLatch latch = new CountDownLatch(1); ZooKeeper zkHandler2;// w w w . j a v a 2s . com //create a new handler with the same sessionId and password zkHandler2 = new ZooKeeper(instance().connectString().get(), sessionTimeout, event -> { if (event.getState() == KeeperState.SyncConnected) { latch.countDown(); } }, zkHandler1.getSessionId(), zkHandler1.getSessionPasswd()); latch.await(); //once connected, close the new handler to cause the original handler session expire zkHandler2.close(); for (KeeperState state : expectedStates) { assertEquals(state, endpointGroup.stateQueue().take()); } testGetEndpointGroup(); }
From source file:com.linecorp.armeria.server.zookeeper.ZooKeeperRegistrationTest.java
License:Apache License
@Ignore // FIXME: https://github.com/line/armeria/issues/477 @Test/*from w w w.j a v a 2 s . c om*/ public void testConnectionRecovery() throws Exception { ZooKeeperRegistration zkConnector = zkConnectors.get(0); zkConnector.enableStateRecording(); ZooKeeper zkHandler1 = zkConnector.underlyingClient(); CountDownLatch latch = new CountDownLatch(1); ZooKeeper zkHandler2; //create a new handler with the same sessionId and password zkHandler2 = new ZooKeeper(instance().connectString().get(), sessionTimeout, event -> { if (event.getState() == KeeperState.SyncConnected) { latch.countDown(); } }, zkHandler1.getSessionId(), zkHandler1.getSessionPasswd()); latch.await(); //once connected, close the new handler to cause the original handler session expire zkHandler2.close(); for (KeeperState state : expectedStates) { assertEquals(state, zkConnector.stateQueue().take()); } //connection will recover and our ZooKeeper node also exists testServerNodeCreateAndDelete(); }