Example usage for org.apache.zookeeper Watcher Watcher

List of usage examples for org.apache.zookeeper Watcher Watcher

Introduction

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

Prototype

Watcher

Source Link

Usage

From source file:com.continuuity.weave.internal.kafka.client.KafkaBrokerCache.java

License:Open Source License

private void getTopics() {
    final String topicsPath = BROKERS_PATH + "/topics";
    Futures.addCallback(zkClient.getChildren(topicsPath, new Watcher() {
        @Override/*from ww w. j a  va2  s  .co m*/
        public void process(WatchedEvent event) {
            getTopics();
        }
    }), new ExistsOnFailureFutureCallback<NodeChildren>(topicsPath, invokeGetTopics) {
        @Override
        public void onSuccess(NodeChildren result) {
            Set<String> children = ImmutableSet.copyOf(result.getChildren());

            // Process new children
            for (String topic : ImmutableSet.copyOf(Sets.difference(children, topicBrokers.keySet()))) {
                getTopic(topicsPath + "/" + topic, topic);
            }

            // Remove old children
            removeDiff(children, topicBrokers);
        }
    });
}

From source file:com.continuuity.weave.internal.kafka.client.KafkaBrokerCache.java

License:Open Source License

private void getTopic(final String path, final String topic) {
    Futures.addCallback(zkClient.getChildren(path, new Watcher() {
        @Override//from  w w  w.  j ava2s. co m
        public void process(WatchedEvent event) {
            // Other event type changes are either could be ignored or handled by parent watcher
            if (event.getType() == Event.EventType.NodeChildrenChanged) {
                getTopic(path, topic);
            }
        }
    }), new FutureCallback<NodeChildren>() {
        @Override
        public void onSuccess(NodeChildren result) {
            List<String> children = result.getChildren();
            final List<ListenableFuture<BrokerPartition>> futures = Lists
                    .newArrayListWithCapacity(children.size());

            // Fetch data from each broken node
            for (final String brokerId : children) {
                Futures.transform(zkClient.getData(path + "/" + brokerId),
                        new Function<NodeData, BrokerPartition>() {
                            @Override
                            public BrokerPartition apply(NodeData input) {
                                return new BrokerPartition(brokerId,
                                        Integer.parseInt(new String(input.getData(), Charsets.UTF_8)));
                            }
                        });
            }

            // When all fetching is done, build the partition size->broker map for this topic
            Futures.successfulAsList(futures).addListener(new Runnable() {
                @Override
                public void run() {
                    Map<Integer, Set<String>> partitionBrokers = Maps.newHashMap();
                    for (ListenableFuture<BrokerPartition> future : futures) {
                        try {
                            BrokerPartition info = future.get();
                            Set<String> brokerSet = partitionBrokers.get(info.getPartitionSize());
                            if (brokerSet == null) {
                                brokerSet = Sets.newHashSet();
                                partitionBrokers.put(info.getPartitionSize(), brokerSet);
                            }
                            brokerSet.add(info.getBrokerId());
                        } catch (Exception e) {
                            // Exception is ignored, as it will be handled by parent watcher
                        }
                    }
                    topicBrokers.put(topic, ImmutableSortedMap.copyOf(partitionBrokers));
                }
            }, Threads.SAME_THREAD_EXECUTOR);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op. Failure would be handled by parent watcher already (e.g. node not exists -> children change in parent)
        }
    });
}

From source file:com.continuuity.weave.internal.state.ZKServiceDecorator.java

License:Open Source License

private Watcher createConnectionWatcher() {
    final AtomicReference<Watcher.Event.KeeperState> keeperState = new AtomicReference<Watcher.Event.KeeperState>();

    return new Watcher() {
        @Override/*from w ww .  j  ava 2 s  .  c om*/
        public void process(WatchedEvent event) {
            // When connected (either first time or reconnected from expiration), creates a ephemeral node
            Event.KeeperState current = event.getState();
            Event.KeeperState previous = keeperState.getAndSet(current);

            LOG.info("Connection state changed " + previous + " => " + current);

            if (current == Event.KeeperState.SyncConnected
                    && (previous == null || previous == Event.KeeperState.Expired)) {
                String liveNode = "/instances/" + id;
                LOG.info("Create live node " + liveNode);

                JsonObject content = new JsonObject();
                content.add("data", liveNodeData.get());
                listenFailure(zkClient.create(liveNode, encodeJson(content), CreateMode.EPHEMERAL));
            }
        }
    };
}

From source file:com.continuuity.weave.internal.state.ZKServiceDecorator.java

License:Open Source License

private void watchMessages() {
    final String messagesPath = getZKPath("messages");
    Futures.addCallback(zkClient.getChildren(messagesPath, new Watcher() {
        @Override/*from  w w w  .  j  av a2 s .c  o  m*/
        public void process(WatchedEvent event) {
            // TODO: Do we need to deal with other type of events?
            if (event.getType() == Event.EventType.NodeChildrenChanged && decoratedService.isRunning()) {
                watchMessages();
            }
        }
    }), new FutureCallback<NodeChildren>() {
        @Override
        public void onSuccess(NodeChildren result) {
            // Sort by the name, which is the messageId. Assumption is that message ids is ordered by time.
            List<String> messages = Lists.newArrayList(result.getChildren());
            Collections.sort(messages);
            for (String messageId : messages) {
                processMessage(messagesPath + "/" + messageId, messageId);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            // TODO: what could be done besides just logging?
            LOG.error("Failed to watch messages.", t);
        }
    });
}

From source file:com.continuuity.weave.internal.zookeeper.DefaultZKClientService.java

License:Open Source License

/**
 * Wraps the given watcher to be called from the event executor.
 * @param watcher Watcher to be wrapped//from   w  ww.ja va 2s . com
 * @return The wrapped Watcher
 */
private Watcher wrapWatcher(final Watcher watcher) {
    if (watcher == null) {
        return null;
    }
    return new Watcher() {
        @Override
        public void process(final WatchedEvent event) {
            eventExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        watcher.process(event);
                    } catch (Throwable t) {
                        LOG.error("Watcher throws exception.", t);
                    }
                }
            });
        }
    };
}

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./*  w  ww.j  a  v a 2  s.  c o m*/
 *
 * @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.continuuity.weave.zookeeper.ZKOperations.java

License:Open Source License

public static void watchDeleted(final ZKClient zkClient, final String path,
        final SettableFuture<String> completion) {

    Futures.addCallback(zkClient.exists(path, new Watcher() {
        @Override//from   w w w.ja  v  a  2  s  . co m
        public void process(WatchedEvent event) {
            if (!completion.isDone()) {
                if (event.getType() == Event.EventType.NodeDeleted) {
                    completion.set(path);
                } else {
                    watchDeleted(zkClient, path, completion);
                }
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            if (result == null) {
                completion.set(path);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            completion.setException(t);
        }
    });
}

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

License:Open Source License

/**
 * Watch for the given path until it exists.
 * @param zkClient The {@link ZKClient} to use.
 * @param path A ZooKeeper path to watch for existent.
 *///from w ww .  ja  v a2  s .  c  om
private static void watchExists(final ZKClient zkClient, final String path,
        final SettableFuture<String> completion) {
    Futures.addCallback(zkClient.exists(path, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (!completion.isDone()) {
                watchExists(zkClient, path, completion);
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            if (result != null) {
                completion.set(path);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            completion.setException(t);
        }
    });
}

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

License:Open Source License

private static <T> void watchChanges(final Operation<T> operation, final String path,
        final Callback<T> callback, final AtomicBoolean cancelled) {
    Futures.addCallback(operation.exec(path, new Watcher() {
        @Override/*  w ww .  ja v  a 2  s .  c  o  m*/
        public void process(WatchedEvent event) {
            if (!cancelled.get()) {
                watchChanges(operation, path, callback, cancelled);
            }
        }
    }), new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            if (!cancelled.get()) {
                callback.updated(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException && ((KeeperException) t).code() == KeeperException.Code.NONODE) {
                final SettableFuture<String> existCompletion = SettableFuture.create();
                existCompletion.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!cancelled.get()) {
                                watchChanges(operation, existCompletion.get(), callback, cancelled);
                            }
                        } catch (Exception e) {
                            LOG.error("Failed to watch children for path " + path, e);
                        }
                    }
                }, Threads.SAME_THREAD_EXECUTOR);
                watchExists(operation.getZKClient(), path, existCompletion);
                return;
            }
            LOG.error("Failed to watch data for path " + path + " " + t, t);
        }
    });
}

From source file:com.deem.zkui.utils.ZooKeeperUtil.java

License:Open Source License

public ZooKeeper createZKConnection(String url, Integer zkSessionTimeout)
        throws IOException, InterruptedException {
    Integer connectAttempt = 0;/*from w  w  w . j a  va2  s  . c  o m*/
    ZooKeeper zk = new ZooKeeper(url, zkSessionTimeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            logger.trace("Connecting to ZK.");
        }
    });
    //Wait till connection is established.
    while (zk.getState() != ZooKeeper.States.CONNECTED) {
        Thread.sleep(30);
        connectAttempt++;
        if (connectAttempt == MAX_CONNECT_ATTEMPT) {
            break;
        }
    }
    return zk;

}