Search in sources :

Example 86 with WatchedEvent

use of org.apache.zookeeper.WatchedEvent in project zookeeper by apache.

the class ClientTest method performClientTest.

private void performClientTest(boolean withWatcherObj) throws IOException, InterruptedException, KeeperException {
    ZooKeeper zk = null;
    try {
        MyWatcher watcher = new MyWatcher();
        zk = createClient(watcher, hostPort);
        LOG.info("Before create /benwashere");
        zk.create("/benwashere", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        LOG.info("After create /benwashere");
        try {
            zk.setData("/benwashere", "hi".getBytes(), 57);
            fail("Should have gotten BadVersion exception");
        } catch (KeeperException.BadVersionException e) {
        // expected that
        } catch (KeeperException e) {
            fail("Should have gotten BadVersion exception");
        }
        LOG.info("Before delete /benwashere");
        zk.delete("/benwashere", 0);
        LOG.info("After delete /benwashere");
        zk.close();
        Thread.sleep(2000);
        zk = createClient(watcher, hostPort);
        LOG.info("Before delete /");
        try {
            zk.delete("/", -1);
            fail("deleted root!");
        } catch (KeeperException.BadArgumentsException e) {
        // good, expected that
        }
        Stat stat = new Stat();
        // Test basic create, ls, and getData
        zk.create("/pat", "Pat was here".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        LOG.info("Before create /ben");
        zk.create("/pat/ben", "Ben was here".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        LOG.info("Before getChildren /pat");
        List<String> children = zk.getChildren("/pat", false);
        assertEquals(1, children.size());
        assertEquals("ben", children.get(0));
        List<String> children2 = zk.getChildren("/pat", false, null);
        assertEquals(children, children2);
        String value = new String(zk.getData("/pat/ben", false, stat));
        assertEquals("Ben was here", value);
        try {
            if (withWatcherObj) {
                assertEquals(null, zk.exists("/frog", watcher));
            } else {
                assertEquals(null, zk.exists("/frog", true));
            }
            LOG.info("Comment: asseting passed for frog setting /");
        } catch (KeeperException.NoNodeException e) {
        // OK, expected that
        }
        zk.create("/frog", "hi".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        // the first poll is just a session delivery
        LOG.info("Comment: checking for events length {}", watcher.events.size());
        WatchedEvent event = watcher.events.poll(10, TimeUnit.SECONDS);
        assertEquals("/frog", event.getPath());
        assertEquals(EventType.NodeCreated, event.getType());
        assertEquals(KeeperState.SyncConnected, event.getState());
        // Test child watch and create with sequence
        zk.getChildren("/pat/ben", true);
        for (int i = 0; i < 10; i++) {
            zk.create("/pat/ben/" + i + "-", Integer.toString(i).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        }
        children = zk.getChildren("/pat/ben", false);
        Collections.sort(children);
        assertEquals(10, children.size());
        for (int i = 0; i < 10; i++) {
            final String name = children.get(i);
            assertTrue(name.startsWith(i + "-"), "starts with -");
            byte[] b;
            if (withWatcherObj) {
                b = zk.getData("/pat/ben/" + name, watcher, stat);
            } else {
                b = zk.getData("/pat/ben/" + name, true, stat);
            }
            assertEquals(Integer.toString(i), new String(b));
            zk.setData("/pat/ben/" + name, "new".getBytes(), stat.getVersion());
            if (withWatcherObj) {
                stat = zk.exists("/pat/ben/" + name, watcher);
            } else {
                stat = zk.exists("/pat/ben/" + name, true);
            }
            zk.delete("/pat/ben/" + name, stat.getVersion());
        }
        event = watcher.events.poll(10, TimeUnit.SECONDS);
        assertEquals("/pat/ben", event.getPath());
        assertEquals(EventType.NodeChildrenChanged, event.getType());
        assertEquals(KeeperState.SyncConnected, event.getState());
        for (int i = 0; i < 10; i++) {
            event = watcher.events.poll(10, TimeUnit.SECONDS);
            final String name = children.get(i);
            assertEquals("/pat/ben/" + name, event.getPath());
            assertEquals(EventType.NodeDataChanged, event.getType());
            assertEquals(KeeperState.SyncConnected, event.getState());
            event = watcher.events.poll(10, TimeUnit.SECONDS);
            assertEquals("/pat/ben/" + name, event.getPath());
            assertEquals(EventType.NodeDeleted, event.getType());
            assertEquals(KeeperState.SyncConnected, event.getState());
        }
        zk.create("/good\u0040path", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.create("/duplicate", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        try {
            zk.create("/duplicate", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            fail("duplicate create allowed");
        } catch (KeeperException.NodeExistsException e) {
        // OK, expected that
        }
    } finally {
        if (zk != null) {
            zk.close();
        }
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) TestableZooKeeper(org.apache.zookeeper.TestableZooKeeper) Stat(org.apache.zookeeper.data.Stat) KeeperException(org.apache.zookeeper.KeeperException)

Example 87 with WatchedEvent

use of org.apache.zookeeper.WatchedEvent in project zookeeper by apache.

the class ClientTest method testMutipleWatcherObjs.

/**
 * Register multiple watchers and verify that they all get notified and
 * in the right order.
 */
@Test
public void testMutipleWatcherObjs() throws IOException, InterruptedException, KeeperException {
    ZooKeeper zk = createClient(new CountdownWatcher(), hostPort);
    try {
        MyWatcher[] watchers = new MyWatcher[100];
        MyWatcher[] watchers2 = new MyWatcher[watchers.length];
        for (int i = 0; i < watchers.length; i++) {
            watchers[i] = new MyWatcher();
            watchers2[i] = new MyWatcher();
            zk.create("/foo-" + i, ("foodata" + i).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        Stat stat = new Stat();
        // 
        for (int i = 0; i < watchers.length; i++) {
            assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
        }
        for (int i = 0; i < watchers.length; i++) {
            assertNotNull(zk.exists("/foo-" + i, watchers[i]));
        }
        // trigger the watches
        for (int i = 0; i < watchers.length; i++) {
            zk.setData("/foo-" + i, ("foodata2-" + i).getBytes(), -1);
            zk.setData("/foo-" + i, ("foodata3-" + i).getBytes(), -1);
        }
        for (int i = 0; i < watchers.length; i++) {
            WatchedEvent event = watchers[i].events.poll(10, TimeUnit.SECONDS);
            assertEquals("/foo-" + i, event.getPath());
            assertEquals(EventType.NodeDataChanged, event.getType());
            assertEquals(KeeperState.SyncConnected, event.getState());
            // small chance that an unexpected message was delivered
            // after this check, but we would catch that next time
            // we check events
            assertEquals(0, watchers[i].events.size());
        }
        // 
        for (int i = 0; i < watchers.length; i++) {
            assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
            assertNotNull(zk.exists("/foo-" + i, watchers[i]));
        }
        // trigger the watches
        for (int i = 0; i < watchers.length; i++) {
            zk.setData("/foo-" + i, ("foodata4-" + i).getBytes(), -1);
            zk.setData("/foo-" + i, ("foodata5-" + i).getBytes(), -1);
        }
        for (int i = 0; i < watchers.length; i++) {
            WatchedEvent event = watchers[i].events.poll(10, TimeUnit.SECONDS);
            assertEquals("/foo-" + i, event.getPath());
            assertEquals(EventType.NodeDataChanged, event.getType());
            assertEquals(KeeperState.SyncConnected, event.getState());
            // small chance that an unexpected message was delivered
            // after this check, but we would catch that next time
            // we check events
            assertEquals(0, watchers[i].events.size());
        }
        // 
        for (int i = 0; i < watchers.length; i++) {
            assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
            assertNotNull(zk.exists("/foo-" + i, watchers2[i]));
        }
        // trigger the watches
        for (int i = 0; i < watchers.length; i++) {
            zk.setData("/foo-" + i, ("foodata6-" + i).getBytes(), -1);
            zk.setData("/foo-" + i, ("foodata7-" + i).getBytes(), -1);
        }
        for (int i = 0; i < watchers.length; i++) {
            WatchedEvent event = watchers[i].events.poll(10, TimeUnit.SECONDS);
            assertEquals("/foo-" + i, event.getPath());
            assertEquals(EventType.NodeDataChanged, event.getType());
            assertEquals(KeeperState.SyncConnected, event.getState());
            // small chance that an unexpected message was delivered
            // after this check, but we would catch that next time
            // we check events
            assertEquals(0, watchers[i].events.size());
            // watchers2
            WatchedEvent event2 = watchers2[i].events.poll(10, TimeUnit.SECONDS);
            assertEquals("/foo-" + i, event2.getPath());
            assertEquals(EventType.NodeDataChanged, event2.getType());
            assertEquals(KeeperState.SyncConnected, event2.getState());
            // small chance that an unexpected message was delivered
            // after this check, but we would catch that next time
            // we check events
            assertEquals(0, watchers2[i].events.size());
        }
    } finally {
        if (zk != null) {
            zk.close();
        }
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) TestableZooKeeper(org.apache.zookeeper.TestableZooKeeper) Stat(org.apache.zookeeper.data.Stat) Test(org.junit.jupiter.api.Test)

Example 88 with WatchedEvent

use of org.apache.zookeeper.WatchedEvent in project jstorm by alibaba.

the class Zookeeper method mkClient.

/**
 * connect ZK, register watchers
 */
public CuratorFramework mkClient(Map conf, List<String> servers, Object port, String root, final WatcherCallBack watcher) {
    CuratorFramework fk = Utils.newCurator(conf, servers, port, root);
    fk.getCuratorListenable().addListener(new CuratorListener() {

        @Override
        public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception {
            if (e.getType().equals(CuratorEventType.WATCHED)) {
                WatchedEvent event = e.getWatchedEvent();
                watcher.execute(event.getState(), event.getType(), event.getPath());
            }
        }
    });
    fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {

        @Override
        public void unhandledError(String msg, Throwable error) {
            String errmsg = "Unrecoverable zookeeper error, halting process: " + msg;
            LOG.error(errmsg, error);
            JStormUtils.halt_process(1, "Unrecoverable zookeeper error");
        }
    });
    fk.start();
    return fk;
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) CuratorFramework(org.apache.curator.framework.CuratorFramework) CuratorListener(org.apache.curator.framework.api.CuratorListener) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) UnhandledErrorListener(org.apache.curator.framework.api.UnhandledErrorListener) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException)

Example 89 with WatchedEvent

use of org.apache.zookeeper.WatchedEvent in project KeptCollections by anthonyu.

the class KeptLock method lockIt.

private boolean lockIt(final long t, final TimeUnit tu) throws KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    // convert the given time to milliseconds and add it to the current time
    final long last = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(t, tu);
    do if (this.keeper.exists(this.znode, new Watcher() {

        @Override
        public void process(final WatchedEvent event) {
            if (event.getType() == EventType.NodeDeleted)
                latch.countDown();
            else if (event.getType() == EventType.NodeCreated)
                // ignore it
                ;
            else
                throw new RuntimeException("unexpected event type" + event.getType());
        }
    }) != null) {
        if (!latch.await(t, tu))
            try {
                this.keeper.create(this.znode, ManagementFactory.getRuntimeMXBean().getName().getBytes(), this.acl, CreateMode.EPHEMERAL);
                return true;
            } catch (final KeeperException.NodeExistsException e) {
            // ignore it
            } catch (final KeeperException e) {
                throw e;
            }
        else
            return false;
    } else
        try {
            this.keeper.create(this.znode, ManagementFactory.getRuntimeMXBean().getName().getBytes(), this.acl, CreateMode.EPHEMERAL);
            return true;
        } catch (final KeeperException.NodeExistsException e) {
        // ignore it
        } catch (final KeeperException e) {
            throw e;
        } while (System.currentTimeMillis() < last);
    return false;
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) Watcher(org.apache.zookeeper.Watcher) CountDownLatch(java.util.concurrent.CountDownLatch) KeeperException(org.apache.zookeeper.KeeperException)

Example 90 with WatchedEvent

use of org.apache.zookeeper.WatchedEvent in project open-kilda by telstra.

the class ZkWriterTest method testProcess.

@Test
public void testProcess() throws KeeperException, InterruptedException, IOException {
    ZkWriter writer = Mockito.mock(ZkWriter.class);
    doCallRealMethod().when(writer).process(any());
    writer.process(new WatchedEvent(EventType.NodeDataChanged, KeeperState.SyncConnected, "/test"));
    verify(writer, Mockito.times(1)).refreshConnectionIfNeeded(KeeperState.SyncConnected);
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) Test(org.junit.Test)

Aggregations

WatchedEvent (org.apache.zookeeper.WatchedEvent)194 Watcher (org.apache.zookeeper.Watcher)123 ZooKeeper (org.apache.zookeeper.ZooKeeper)67 CountDownLatch (java.util.concurrent.CountDownLatch)64 KeeperException (org.apache.zookeeper.KeeperException)56 Test (org.junit.Test)38 Stat (org.apache.zookeeper.data.Stat)35 IOException (java.io.IOException)31 Test (org.testng.annotations.Test)27 Test (org.junit.jupiter.api.Test)18 CuratorFramework (org.apache.curator.framework.CuratorFramework)14 AsyncCallback (org.apache.zookeeper.AsyncCallback)14 List (java.util.List)10 KeeperState (org.apache.zookeeper.Watcher.Event.KeeperState)10 Set (java.util.Set)7 TimeoutException (java.util.concurrent.TimeoutException)7 HashSet (java.util.HashSet)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 RetryOneTime (org.apache.curator.retry.RetryOneTime)6