Example usage for org.apache.zookeeper ZooKeeper close

List of usage examples for org.apache.zookeeper ZooKeeper close

Introduction

In this page you can find the example usage for org.apache.zookeeper ZooKeeper close.

Prototype

public synchronized void close() throws InterruptedException 

Source Link

Document

Close this client object.

Usage

From source file:blazingcache.server.SimpleZKSecureTest.java

@Test
public void sessionExpirationTest_SingleCacheServer() throws Exception {
    byte[] data = "testdata".getBytes(StandardCharsets.UTF_8);
    ServerHostData hostData = new ServerHostData("localhost", 1234, "ciao", false, null);
    try (ZKTestEnv zkEnv = new ZKTestEnv(folderZk.getRoot().toPath());
            CacheServer cacheServer = new CacheServer("ciao", hostData)) {
        cacheServer.setupCluster(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath(), hostData, true);
        cacheServer.start();//from   ww  w  .  ja  v a  2  s  .  c om

        try (CacheClient client1 = new CacheClient("theClient1", "ciao",
                new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()));
                CacheClient client2 = new CacheClient("theClient2", "ciao",
                        new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()))) {
            client1.start();
            client2.start();

            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));

            client1.put("pippo", data, 0);
            client2.put("pippo", data, 0);

            Assert.assertArrayEquals(data, client1.get("pippo").getSerializedData());
            Assert.assertArrayEquals(data, client2.get("pippo").getSerializedData());

            assertEquals(1, client1.getCacheSize());
            assertEquals(1, client2.getCacheSize());

            final long lastStateChangeTS = cacheServer.getStateChangeTimestamp();
            /*
             * Make's ZooKeeper's session expire:
             *
             * this is the session id and password to use on a second zookeeper
             * handle so as to make service monitor's handle to expire
             */
            final long serviceZKSessionId = cacheServer.getZooKeeper().getSessionId();
            final byte[] serviceZKpasswd = cacheServer.getZooKeeper().getSessionPasswd();

            CountdownWatcher watch2 = new CountdownWatcher("zkexpire");
            // make session on cache server's cluster manager zk handle expire
            final ZooKeeper zk = new ZooKeeper(zkEnv.getAddress(), zkEnv.getTimeout(), watch2,
                    serviceZKSessionId, serviceZKpasswd);
            watch2.waitForConnected(10000);
            zk.close();
            //first things first, make sure leadership is lost: state change ts has changed
            waitForCondition(() -> {
                return cacheServer.getStateChangeTimestamp() > lastStateChangeTS;
            }, 100);
            //when fake zk handle expires we are sure that origina cache server session is going to expire
            watch2.waitForExpired(10000);
            //first things first, make sure leadership is acquired again
            waitForCondition(() -> {
                return cacheServer.isLeader();
            }, 100);

            //ensure clients reconnect
            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));
            assertEquals(0, client1.getCacheSize());
            assertEquals(0, client2.getCacheSize());
        }
    }
}

From source file:blazingcache.server.SimpleZKSecureTest.java

@Test
public void sessionExpirationTest_BackupServer() throws Exception {
    byte[] data = "testdata".getBytes(StandardCharsets.UTF_8);
    final ServerHostData leaderHostdata = new ServerHostData("localhost", 1234, "leader", false, null);
    final ServerHostData backupHostdata = new ServerHostData("localhost", 1235, "backup", false, null);
    try (ZKTestEnv zkEnv = new ZKTestEnv(folderZk.getRoot().toPath());
            CacheServer cacheServer = new CacheServer("ciao", leaderHostdata);
            CacheServer cacheServerBk = new CacheServer("ciao", backupHostdata)) {

        cacheServer.setupCluster(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath(), leaderHostdata, true);
        cacheServer.start();//from   w  ww  . ja  va 2 s . c  om
        waitForCondition(() -> {
            return cacheServer.isLeader();
        }, 100);

        //start backupcluster: we are sure this is in backup mode
        cacheServerBk.setupCluster(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath(), backupHostdata,
                true);
        cacheServerBk.start();

        try (CacheClient client1 = new CacheClient("theClient1", "ciao",
                new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()));
                CacheClient client2 = new CacheClient("theClient2", "ciao",
                        new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()))) {
            client1.start();
            client2.start();

            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));

            client1.put("pippo", data, 0);
            client2.put("pippo", data, 0);

            Assert.assertArrayEquals(data, client1.get("pippo").getSerializedData());
            Assert.assertArrayEquals(data, client2.get("pippo").getSerializedData());

            assertEquals(1, client1.getCacheSize());
            assertEquals(1, client2.getCacheSize());

            final long lastStateChangeTS = cacheServer.getStateChangeTimestamp();
            /*
             * Make's ZooKeeper's session expire:
             *
             * this is the session id and password to use on a second zookeeper
             * handle so as to make service monitor's handle to expire
             */
            final long serviceZKSessionId = cacheServer.getZooKeeper().getSessionId();
            final byte[] serviceZKpasswd = cacheServer.getZooKeeper().getSessionPasswd();

            CountdownWatcher watch2 = new CountdownWatcher("zkexpire");
            // make session on cache server's cluster manager zk handle expire
            final ZooKeeper zk = new ZooKeeper(zkEnv.getAddress(), zkEnv.getTimeout(), watch2,
                    serviceZKSessionId, serviceZKpasswd);
            watch2.waitForConnected(10000);
            zk.close();
            //first things first, make sure leadership is lost: state change ts has changed
            waitForCondition(() -> {
                return cacheServer.getStateChangeTimestamp() > lastStateChangeTS;
            }, 100);
            //when fake zk handle expires we are sure that original cache server session is going to expire
            watch2.waitForExpired(10000);
            //first things first, make sure leadership is acquired again
            waitForCondition(() -> {
                return client1.getCacheSize() == 0 && client2.getCacheSize() == 0;
            }, 100);
            waitForCondition(() -> {
                return !cacheServer.isLeader();
            }, 100);
            waitForCondition(() -> {
                return cacheServerBk.isLeader();
            }, 100);

            //ensure clients reconnect
            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));

            client1.put("pippo", data, 0);
            client2.put("pippo", data, 0);

            Assert.assertArrayEquals(data, client1.get("pippo").getSerializedData());
            Assert.assertArrayEquals(data, client2.get("pippo").getSerializedData());

            assertEquals(1, client1.getCacheSize());
            assertEquals(1, client2.getCacheSize());

            client1.invalidate("pippo");
            assertNull(client1.get("pippo"));
            assertNull(client2.get("pippo"));
            assertEquals(0, client1.getCacheSize());
            assertEquals(0, client2.getCacheSize());
        }
    }
}

From source file:blazingcache.server.SimpleZKTest.java

@Test
public void sessionExpirationTest_SingleCacheServer() throws Exception {
    byte[] data = "testdata".getBytes(StandardCharsets.UTF_8);
    ServerHostData hostData = new ServerHostData("localhost", 1234, "ciao", false, null);
    try (ZKTestEnv zkEnv = new ZKTestEnv(folderZk.getRoot().toPath());
            CacheServer cacheServer = new CacheServer("ciao", hostData)) {
        cacheServer.setupCluster(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath(), hostData, false);
        cacheServer.start();/*from w ww . j a v  a  2s . c o  m*/

        try (CacheClient client1 = new CacheClient("theClient1", "ciao",
                new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()));
                CacheClient client2 = new CacheClient("theClient2", "ciao",
                        new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()))) {
            client1.start();
            client2.start();

            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));

            client1.put("pippo", data, 0);
            client2.put("pippo", data, 0);

            Assert.assertArrayEquals(data, client1.get("pippo").getSerializedData());
            Assert.assertArrayEquals(data, client2.get("pippo").getSerializedData());

            assertEquals(1, client1.getCacheSize());
            assertEquals(1, client2.getCacheSize());

            final long lastStateChangeTS = cacheServer.getStateChangeTimestamp();
            /*
             * Make's ZooKeeper's session expire:
             *
             * this is the session id and password to use on a second zookeeper
             * handle so as to make service monitor's handle to expire
             */
            final long serviceZKSessionId = cacheServer.getZooKeeper().getSessionId();
            final byte[] serviceZKpasswd = cacheServer.getZooKeeper().getSessionPasswd();

            CountdownWatcher watch2 = new CountdownWatcher("zkexpire");
            // make session on cache server's cluster manager zk handle expire
            final ZooKeeper zk = new ZooKeeper(zkEnv.getAddress(), zkEnv.getTimeout(), watch2,
                    serviceZKSessionId, serviceZKpasswd);
            watch2.waitForConnected(10000);
            zk.close();
            //first things first, make sure leadership is lost: state change ts has changed
            waitForCondition(() -> {
                return cacheServer.getStateChangeTimestamp() > lastStateChangeTS;
            }, 100);
            //when fake zk handle expires we are sure that origina cache server session is going to expire
            watch2.waitForExpired(10000);
            //first things first, make sure leadership is acquired again
            waitForCondition(() -> {
                return cacheServer.isLeader();
            }, 100);

            //ensure clients reconnect
            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));
            assertEquals(0, client1.getCacheSize());
            assertEquals(0, client2.getCacheSize());
        }
    }
}

From source file:blazingcache.server.SimpleZKTest.java

@Test
public void sessionExpirationTest_BackupServer() throws Exception {
    byte[] data = "testdata".getBytes(StandardCharsets.UTF_8);
    final ServerHostData leaderHostdata = new ServerHostData("localhost", 1234, "leader", false, null);
    final ServerHostData backupHostdata = new ServerHostData("localhost", 1235, "backup", false, null);
    try (ZKTestEnv zkEnv = new ZKTestEnv(folderZk.getRoot().toPath());
            CacheServer cacheServer = new CacheServer("ciao", leaderHostdata);
            CacheServer cacheServerBk = new CacheServer("ciao", backupHostdata)) {

        cacheServer.setupCluster(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath(), leaderHostdata,
                false);/*  w  ww.  j  av  a 2s . c o m*/
        cacheServer.start();
        waitForCondition(() -> {
            return cacheServer.isLeader();
        }, 100);

        //start backupcluster: we are sure this is in backup mode
        cacheServerBk.setupCluster(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath(), backupHostdata,
                false);
        cacheServerBk.start();

        try (CacheClient client1 = new CacheClient("theClient1", "ciao",
                new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()));
                CacheClient client2 = new CacheClient("theClient2", "ciao",
                        new ZKCacheServerLocator(zkEnv.getAddress(), zkEnv.getTimeout(), zkEnv.getPath()))) {
            client1.start();
            client2.start();

            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));

            client1.put("pippo", data, 0);
            client2.put("pippo", data, 0);

            Assert.assertArrayEquals(data, client1.get("pippo").getSerializedData());
            Assert.assertArrayEquals(data, client2.get("pippo").getSerializedData());

            assertEquals(1, client1.getCacheSize());
            assertEquals(1, client2.getCacheSize());

            final long lastStateChangeTS = cacheServer.getStateChangeTimestamp();
            /*
             * Make's ZooKeeper's session expire:
             *
             * this is the session id and password to use on a second zookeeper
             * handle so as to make service monitor's handle to expire
             */
            final long serviceZKSessionId = cacheServer.getZooKeeper().getSessionId();
            final byte[] serviceZKpasswd = cacheServer.getZooKeeper().getSessionPasswd();

            CountdownWatcher watch2 = new CountdownWatcher("zkexpire");
            // make session on cache server's cluster manager zk handle expire
            final ZooKeeper zk = new ZooKeeper(zkEnv.getAddress(), zkEnv.getTimeout(), watch2,
                    serviceZKSessionId, serviceZKpasswd);
            watch2.waitForConnected(10000);
            zk.close();
            //first things first, make sure leadership is lost: state change ts has changed
            waitForCondition(() -> {
                return cacheServer.getStateChangeTimestamp() > lastStateChangeTS;
            }, 100);
            //when fake zk handle expires we are sure that original cache server session is going to expire
            watch2.waitForExpired(10000);
            //first things first, make sure leadership is acquired again
            waitForCondition(() -> {
                return client1.getCacheSize() == 0 && client2.getCacheSize() == 0;
            }, 100);
            waitForCondition(() -> {
                return !cacheServer.isLeader();
            }, 100);
            waitForCondition(() -> {
                return cacheServerBk.isLeader();
            }, 100);

            //ensure clients reconnect
            assertTrue(client1.waitForConnection(10000));
            assertTrue(client2.waitForConnection(10000));

            client1.put("pippo", data, 0);
            client2.put("pippo", data, 0);

            Assert.assertArrayEquals(data, client1.get("pippo").getSerializedData());
            Assert.assertArrayEquals(data, client2.get("pippo").getSerializedData());

            assertEquals(1, client1.getCacheSize());
            assertEquals(1, client2.getCacheSize());

            client1.invalidate("pippo");
            assertNull(client1.get("pippo"));
            assertNull(client2.get("pippo"));
            assertEquals(0, client1.getCacheSize());
            assertEquals(0, client2.getCacheSize());
        }
    }
}

From source file:blazingcache.zookeeper.ZKCacheServerLocator.java

License:Apache License

@Override
protected ServerHostData getServer() {

    String leaderPath = basePath + "/leader";
    try {//from w w w  . ja  va  2  s  . c om
        byte[] data;
        if (ownedZk) {
            CountDownLatch connection = new CountDownLatch(1);
            try {
                LOGGER.finest("creating temp ZK client for discovery");
                ZooKeeper client = new ZooKeeper(zkAddress, zkSessiontimeout, new Watcher() {

                    @Override
                    public void process(WatchedEvent event) {
                        if (event.getState() == Event.KeeperState.SyncConnected
                                || event.getState() == Event.KeeperState.ConnectedReadOnly) {
                            connection.countDown();
                        }
                        LOGGER.severe("process ZK event " + event.getState() + " " + event.getType() + " "
                                + event.getPath());
                    }
                });
                try {
                    connection.await(connectTimeout, TimeUnit.MILLISECONDS);
                    LOGGER.finest("ZK client is " + client);
                    // se la connessione non sar stabilita in tempo o c' qualche problem troveremo un ConnectionLoss ad esempio                                        
                    data = client.getData(leaderPath, false, null);
                } finally {
                    client.close();
                }
            } catch (IOException err) {
                LOGGER.log(Level.SEVERE, "zookeeper client not available: " + err);
                return null;
            }

        } else {
            ZooKeeper client = zkSupplier.get();
            if (client == null) {
                LOGGER.log(Level.SEVERE, "zookeeper client available");
                return null;
            }
            data = client.getData(leaderPath, false, null);
        }
        lastKnownServer = ServerHostData.parseHostdata(data);
        return lastKnownServer;
    } catch (KeeperException.NoNodeException nobroker) {
        LOGGER.log(Level.SEVERE, "zookeeper client error", nobroker);
        return null;
    } catch (KeeperException | InterruptedException err) {
        LOGGER.log(Level.SEVERE, "zookeeper client error", err);
        return null;
    }
}

From source file:ch.usi.da.paxos.ring.Node.java

License:Open Source License

public void stop() throws InterruptedException {
    for (RingDescription r : rings) {
        RingManager ring = r.getRingManager();
        if (ring.getNetwork().getAcceptor() != null) {
            ((AcceptorRole) ring.getNetwork().getAcceptor()).getStableStorage().close();
        }// w ww  . j ava2  s .  c o  m
        ring.getNetwork().disconnectClient();
        ring.getNetwork().closeServer();
    }
    for (ZooKeeper zoo : zoos) {
        zoo.close();
    }
    running = false;
}

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  w w  .  j  ava2  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

/**
 * Closes the given {@link ZooKeeper} if it is not null. If there is InterruptedException,
 * it will get logged.//from   w ww .  j ava2 s. c  o  m
 */
private void closeZooKeeper(@Nullable ZooKeeper zk) {
    try {
        if (zk != null) {
            zk.close();
        }
    } catch (InterruptedException e) {
        LOG.warn("Interrupted when closing ZooKeeper", e);
        Thread.currentThread().interrupt();
    }
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.ZooKeeperClientTest.java

License:Apache License

@Test
public void testClient() {
    ZkClientx zk = ZooKeeperClient.getInstance();
    // ?zk??//from   ww w .ja  va 2s. 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.alibaba.otter.shared.common.utils.zookeeper.ZooKeeperx.java

License:Apache License

public void configMutliCluster(ZooKeeper zk) {
    if (_servers.size() == 1) {
        return;/*  www  .j  a  v  a2s  .c o m*/
    }
    String cluster1 = _servers.get(0);
    try {
        if (_servers.size() > 1) {
            // accessible
            ReflectionUtils.makeAccessible(clientCnxnField);
            ReflectionUtils.makeAccessible(hostProviderField);
            ReflectionUtils.makeAccessible(serverAddressesField);

            // 
            for (int i = 1; i < _servers.size(); i++) {
                String cluster = _servers.get(i);
                // ?zk??
                ClientCnxn cnxn = (ClientCnxn) ReflectionUtils.getField(clientCnxnField, zk);
                HostProvider hostProvider = (HostProvider) ReflectionUtils.getField(hostProviderField, cnxn);
                List<InetSocketAddress> serverAddrs = (List<InetSocketAddress>) ReflectionUtils
                        .getField(serverAddressesField, hostProvider);
                // 
                serverAddrs.addAll(new ConnectStringParser(cluster).getServerAddresses());
            }
        }
    } catch (Exception e) {
        try {
            if (zk != null) {
                zk.close();
            }
        } catch (InterruptedException ie) {
            // ignore interrupt
        }
        throw new ZkException("zookeeper_create_error, serveraddrs=" + cluster1, e);
    }

}