List of usage examples for org.apache.zookeeper ZooKeeper getSessionTimeout
public int getSessionTimeout()
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//w ww.j av a 2 s. co 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:com.alibaba.otter.shared.arbitrate.zookeeper.ZooKeeperClientTest.java
License:Apache License
@Test public void testClient() { ZkClientx zk = ZooKeeperClient.getInstance(); // ?zk??//from w ww.j a v a2s. c om 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.journal.jini.ha.AbstractHA3JournalServerTestCase.java
License:Open Source License
/** * Return the negotiated zookeeper session timeout in milliseconds (if * available) and otherwise the requested zookeeper session timeout. *//* w w w . j ava 2s. com*/ protected int getZKSessionTimeout() { final ZooKeeper zookeeper = this.zookeeper; if (zookeeper != null) { final int t = zookeeper.getSessionTimeout(); if (t > 0) return t; } ZookeeperClientConfig t = zkClientConfig; if (t != null) { return t.sessionTimeout; } return 10000; }
From source file:com.bigdata.zookeeper.DumpZookeeper.java
License:Open Source License
/** * Dumps the zookeeper znodes for the bigdata federation. * /* w ww .j a v a2 s .co m*/ * @param args * A {@link Configuration} and optional overrides. * * @throws IOException * @throws InterruptedException * @throws KeeperException * @throws ConfigurationException * * TODO Add a listener mode (tail zk events). */ public static void main(final String[] args) throws IOException, InterruptedException, KeeperException, ConfigurationException { final Configuration config = ConfigurationProvider.getInstance(args); final ZookeeperClientConfig zooClientConfig = new ZookeeperClientConfig(config); /* * Note: You may temporarily uncomment this to set the zookeeper * configuration via -D parameters. */ // final ZookeeperClientConfig zooClientConfig = new ZookeeperClientConfig(); System.out.println(zooClientConfig.toString()); // System.err.println(ZooHelper.dump(InetAddress.getLocalHost(), // clientPort)); final boolean showData = true; final ZooKeeper z = new ZooKeeper(zooClientConfig.servers, 2000/* sessionTimeout */, new Watcher() { public void process(WatchedEvent event) { log.info(event); } }); /* * The sessionTimeout as negotiated (effective sessionTimeout). * * Note: This is not available until we actually request something * from zookeeper. */ { try { z.getData(zooClientConfig.zroot, false/* watch */, null/* stat */); } catch (NoNodeException ex) { // Ignore. } catch (KeeperException ex) { // Oops. log.error(ex, ex); } System.out.println("Negotiated sessionTimeout=" + z.getSessionTimeout() + "ms"); } final PrintWriter w = new PrintWriter(System.out); try { // recursive dump. new DumpZookeeper(z).dump(w, showData, zooClientConfig.zroot, 0/* depth */); w.println("----"); w.flush(); } finally { z.close(); w.close(); } }
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 w ww .j a v a 2 s .c o 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.linkedin.d2.discovery.stores.zk.ZKTestUtil.java
License:Apache License
public static void expireSession(String connectString, ZooKeeper zk, long timeout, TimeUnit timeoutUnit) throws IOException, TimeoutException, InterruptedException { expireSession(connectString, zk.getSessionTimeout(), zk.getSessionId(), zk.getSessionPasswd(), timeout, timeoutUnit);/*from w w w.jav a2s . co m*/ }
From source file:com.linkedin.helix.TestZkClientWrapper.java
License:Apache License
@Test() void testSessioExpire() { IZkStateListener listener = new IZkStateListener() { @Override/*www . ja v a 2 s. c om*/ public void handleStateChanged(KeeperState state) throws Exception { System.out.println("In Old connection New state " + state); } @Override public void handleNewSession() throws Exception { System.out.println("In Old connection New session"); } }; _zkClient.subscribeStateChanges(listener); ZkConnection connection = ((ZkConnection) _zkClient.getConnection()); ZooKeeper zookeeper = connection.getZookeeper(); System.out.println("old sessionId= " + zookeeper.getSessionId()); try { Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { System.out.println("In New connection In process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(connection.getServers(), zookeeper.getSessionTimeout(), watcher, zookeeper.getSessionId(), zookeeper.getSessionPasswd()); Thread.sleep(3000); System.out.println("New sessionId= " + newZookeeper.getSessionId()); Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); connection = ((ZkConnection) _zkClient.getConnection()); zookeeper = connection.getZookeeper(); System.out.println("After session expiry sessionId= " + zookeeper.getSessionId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.linkedin.helix.ZkUnitTestBase.java
License:Apache License
protected void simulateSessionExpiry(ZkConnection zkConnection) throws IOException, InterruptedException { ZooKeeper oldZookeeper = zkConnection.getZookeeper(); LOG.info("Old sessionId = " + oldZookeeper.getSessionId()); Watcher watcher = new Watcher() { @Override/*from w ww.ja v a 2 s . c o m*/ public void process(WatchedEvent event) { LOG.info("In New connection, process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(zkConnection.getServers(), oldZookeeper.getSessionTimeout(), watcher, oldZookeeper.getSessionId(), oldZookeeper.getSessionPasswd()); LOG.info("New sessionId = " + newZookeeper.getSessionId()); // Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); oldZookeeper = zkConnection.getZookeeper(); LOG.info("After session expiry sessionId = " + oldZookeeper.getSessionId()); }
From source file:com.linkedin.helix.ZkUnitTestBase.java
License:Apache License
protected void simulateSessionExpiry(ZkClient zkClient) throws IOException, InterruptedException { IZkStateListener listener = new IZkStateListener() { @Override//from w ww. j ava 2 s . c o m public void handleStateChanged(KeeperState state) throws Exception { LOG.info("In Old connection, state changed:" + state); } @Override public void handleNewSession() throws Exception { LOG.info("In Old connection, new session"); } }; zkClient.subscribeStateChanges(listener); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper oldZookeeper = connection.getZookeeper(); LOG.info("Old sessionId = " + oldZookeeper.getSessionId()); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("In New connection, process event:" + event); } }; ZooKeeper newZookeeper = new ZooKeeper(connection.getServers(), oldZookeeper.getSessionTimeout(), watcher, oldZookeeper.getSessionId(), oldZookeeper.getSessionPasswd()); LOG.info("New sessionId = " + newZookeeper.getSessionId()); // Thread.sleep(3000); newZookeeper.close(); Thread.sleep(10000); connection = (ZkConnection) zkClient.getConnection(); oldZookeeper = connection.getZookeeper(); LOG.info("After session expiry sessionId = " + oldZookeeper.getSessionId()); }
From source file:org.apache.bookkeeper.test.ZooKeeperCluster.java
License:Apache License
default void expireSession(ZooKeeper zk) throws Exception { long id = zk.getSessionId(); byte[] password = zk.getSessionPasswd(); ZooKeeperWatcherBase w = new ZooKeeperWatcherBase(10000); ZooKeeper zk2 = new ZooKeeper(getZooKeeperConnectString(), zk.getSessionTimeout(), w, id, password); w.waitForConnection();/*w w w .j ava2 s . co m*/ zk2.close(); }