Search in sources :

Example 11 with Watcher

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

the class QuorumZxidSyncTest method testLateLogs.

/**
     * find out what happens when the latest state is in the snapshots not
     * the logs.
     */
@Test
public void testLateLogs() throws Exception {
    // crank up the epoch numbers
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    ZooKeeper zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {

        public void process(WatchedEvent event) {
        }
    });
    zk.create("/0", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    zk.close();
    qb.shutdownServers();
    qb.startServers();
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    qb.shutdownServers();
    qb.startServers();
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {

        public void process(WatchedEvent event) {
        }
    });
    zk.create("/1", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    zk.close();
    qb.shutdownServers();
    qb.startServers();
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    qb.shutdownServers();
    deleteLogs(qb.s1dir);
    deleteLogs(qb.s2dir);
    deleteLogs(qb.s3dir);
    deleteLogs(qb.s4dir);
    deleteLogs(qb.s5dir);
    qb.startServers();
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {

        public void process(WatchedEvent event) {
        }
    });
    zk.create("/2", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    zk.close();
    qb.shutdownServers();
    qb.startServers();
    ClientBase.waitForServerUp(qb.hostPort, 10000);
    zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {

        public void process(WatchedEvent event) {
        }
    });
    boolean saw2 = false;
    for (String child : zk.getChildren("/", false)) {
        if (child.equals("2")) {
            saw2 = true;
        }
    }
    zk.close();
    Assert.assertTrue("Didn't see /2 (went back in time)", saw2);
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) Watcher(org.apache.zookeeper.Watcher) Test(org.junit.Test)

Example 12 with Watcher

use of org.apache.zookeeper.Watcher in project weave by continuuity.

the class KillZKSession method kill.

/**
   * 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.
   *
   * @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();
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) Watcher(org.apache.zookeeper.Watcher) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 13 with Watcher

use of org.apache.zookeeper.Watcher in project weave by continuuity.

the class ZKOperations method watchData.

/**
   * Watch for data changes of the given path. The callback will be triggered whenever changes has been
   * detected. Note that the callback won't see every single changes, as that's not the guarantee of ZooKeeper.
   * If the node doesn't exists, it will watch for its creation then starts watching for data changes.
   * When the node is deleted afterwards,
   *
   * @param zkClient The {@link ZKClient} for the operation
   * @param path Path to watch
   * @param callback Callback to be invoked when data changes is detected.
   * @return A {@link Cancellable} to cancel the watch.
   */
public static Cancellable watchData(final ZKClient zkClient, final String path, final DataCallback callback) {
    final AtomicBoolean cancelled = new AtomicBoolean(false);
    watchChanges(new Operation<NodeData>() {

        @Override
        public ZKClient getZKClient() {
            return zkClient;
        }

        @Override
        public OperationFuture<NodeData> exec(String path, Watcher watcher) {
            return zkClient.getData(path, watcher);
        }
    }, path, callback, cancelled);
    return new Cancellable() {

        @Override
        public void cancel() {
            cancelled.set(true);
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cancellable(com.continuuity.weave.common.Cancellable) Watcher(org.apache.zookeeper.Watcher) SettableOperationFuture(com.continuuity.weave.internal.zookeeper.SettableOperationFuture)

Example 14 with Watcher

use of org.apache.zookeeper.Watcher in project weave by continuuity.

the class ZKOperations method watchChildren.

public static Cancellable watchChildren(final ZKClient zkClient, String path, ChildrenCallback callback) {
    final AtomicBoolean cancelled = new AtomicBoolean(false);
    watchChanges(new Operation<NodeChildren>() {

        @Override
        public ZKClient getZKClient() {
            return zkClient;
        }

        @Override
        public OperationFuture<NodeChildren> exec(String path, Watcher watcher) {
            return zkClient.getChildren(path, watcher);
        }
    }, path, callback, cancelled);
    return new Cancellable() {

        @Override
        public void cancel() {
            cancelled.set(true);
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cancellable(com.continuuity.weave.common.Cancellable) Watcher(org.apache.zookeeper.Watcher) SettableOperationFuture(com.continuuity.weave.internal.zookeeper.SettableOperationFuture)

Example 15 with Watcher

use of org.apache.zookeeper.Watcher in project weave by continuuity.

the class ZKClientTest method testExpireRewatch.

@Test
public void testExpireRewatch() throws InterruptedException, IOException, ExecutionException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build();
    zkServer.startAndWait();
    try {
        final CountDownLatch expireReconnectLatch = new CountDownLatch(1);
        final AtomicBoolean expired = new AtomicBoolean(false);
        final ZKClientService client = ZKClientServices.delegate(ZKClients.reWatchOnExpire(ZKClientService.Builder.of(zkServer.getConnectionStr()).setSessionTimeout(2000).setConnectionWatcher(new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.Expired) {
                    expired.set(true);
                } else if (event.getState() == Event.KeeperState.SyncConnected && expired.compareAndSet(true, true)) {
                    expireReconnectLatch.countDown();
                }
            }
        }).build()));
        client.startAndWait();
        try {
            final BlockingQueue<Watcher.Event.EventType> events = new LinkedBlockingQueue<Watcher.Event.EventType>();
            client.exists("/expireRewatch", new Watcher() {

                @Override
                public void process(WatchedEvent event) {
                    client.exists("/expireRewatch", this);
                    events.add(event.getType());
                }
            });
            client.create("/expireRewatch", null, CreateMode.PERSISTENT);
            Assert.assertEquals(Watcher.Event.EventType.NodeCreated, events.poll(2, TimeUnit.SECONDS));
            KillZKSession.kill(client.getZooKeeperSupplier().get(), zkServer.getConnectionStr(), 1000);
            Assert.assertTrue(expireReconnectLatch.await(5, TimeUnit.SECONDS));
            client.delete("/expireRewatch");
            Assert.assertEquals(Watcher.Event.EventType.NodeDeleted, events.poll(4, TimeUnit.SECONDS));
        } finally {
            client.stopAndWait();
        }
    } finally {
        zkServer.stopAndWait();
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Watcher(org.apache.zookeeper.Watcher) WatchedEvent(org.apache.zookeeper.WatchedEvent) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) InMemoryZKServer(com.continuuity.weave.internal.zookeeper.InMemoryZKServer) Test(org.junit.Test)

Aggregations

Watcher (org.apache.zookeeper.Watcher)78 WatchedEvent (org.apache.zookeeper.WatchedEvent)62 KeeperException (org.apache.zookeeper.KeeperException)35 CountDownLatch (java.util.concurrent.CountDownLatch)25 ZooKeeper (org.apache.zookeeper.ZooKeeper)25 Stat (org.apache.zookeeper.data.Stat)21 Test (org.junit.Test)18 IOException (java.io.IOException)11 AsyncCallback (org.apache.zookeeper.AsyncCallback)10 List (java.util.List)8 Test (org.testng.annotations.Test)8 None (com.linkedin.common.util.None)7 HashSet (java.util.HashSet)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Map (java.util.Map)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 TimeoutException (java.util.concurrent.TimeoutException)4 CountdownWatcher (org.apache.zookeeper.test.ClientBase.CountdownWatcher)4