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.cloudera.flume.master.TestZKClient.java

License:Apache License

/**
 * Tests bringing up and shutting down a standalone ZooKeeper instance
 *//* w w  w  .j  a v a2 s.c  o m*/
@Test
public void testStandaloneUpAndDown() throws Exception {
    ZKInProcessServer zk = new ZKInProcessServer(2181, "/tmp/flume-test-zk/");
    zk.start();
    ZooKeeper client = new ZooKeeper("localhost:2181", 5000, new Watcher() {
        public void process(WatchedEvent event) {
        }
    });

    Thread.sleep(1000);
    List<String> children = client.getChildren("/", false);
    LOG.warn("Got " + children.size() + " children");
    assertTrue(children.size() > 0);
    zk.stop();
}

From source file:com.cloudera.flume.master.ZKClient.java

License:Apache License

/**
 * Establishes a connection with a cluster of ZooKeeper servers. Throws an
 * IOException on failure.//from   w ww .  j  a  v  a2s  . c  om
 */
public synchronized boolean init(final InitCallback initCallback) throws IOException {
    Preconditions.checkState(this.zk == null, "zk not null in ZKClient.init");
    initCallBack = initCallback;
    final Retryable retry = new Retryable() {
        public boolean doTry() throws Exception {
            // Wait on this latch for a connection to complete
            // It's important that every try gets its own latch
            final CountDownLatch latch = new CountDownLatch(1);
            final Watcher watcher = new Watcher() {
                public void process(WatchedEvent event) {
                    // Don't down the latch if we weren't the most recent attempt
                    if (event.getState() == KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            };

            zk = new ZooKeeper(hosts, 5000, watcher);

            if (!latch.await(5, TimeUnit.SECONDS)) {
                throw new IOException("Could not connect to ZooKeeper!");
            }
            if (initCallback != null) {
                initCallback.success(ZKClient.this);
            }
            return true;
        };
    };
    RetryHarness harness = new RetryHarness(retry, new FixedRetryPolicy(3), true);

    try {
        return harness.attempt();
    } catch (IOException i) {
        throw i;
    } catch (Exception e) {
        throw new IOException("Unexpected exception connecting to ZK", e);
    }
}

From source file:com.comcast.viper.flume2storm.location.DynamicLocationService.java

License:Apache License

/**
 * Updates the list of active {@link ServiceProvider} servers, and sets a
 * watch so that we get notified if the list changes
 *///  w  ww  .  j a v a2 s .co  m
protected synchronized void getServiceInstances() {
    if (!zkClient.getState().isConnected()) {
        return;
    }
    final Watcher watcher = new Watcher() {
        @Override
        public void process(final WatchedEvent event) {
            LOG.debug("Service node watch triggered with event: {}", event);
            getServiceInstances();
        }
    };
    try {
        final List<String> res = new ZkOperation(zkClient, servicePath).getChildren(watcher);
        final Collection<SP> newList = new ArrayList<SP>();
        for (final String child : res) {
            final String childPath = ZkUtilies.buildZkPath(servicePath, child);
            try {
                final byte[] bytes = new ZkOperation(zkClient, childPath).getData();
                newList.add(serviceProviderSerialization.deserialize(bytes));
            } catch (final KeeperException.NoNodeException nne) {
                // Programming note: The node was removed been the time we
                // got the
                // list and the parsing time... no big deal
                LOG.debug("znode {} disappear: {}", childPath, nne.getLocalizedMessage());
            } catch (final Exception e) {
                LOG.warn("Failed to deserialize znode " + childPath, e);
            }
        }
        serviceProviderManager.set(newList);
    } catch (final Exception e) {
        if (zkClient.getState().isConnected()) {
            LOG.error("Failed to get service instances", e);
        }
        // Otherwise, we might have a clue why this is failing! :)
    }
}

From source file:com.consol.citrus.zookeeper.client.ZooClient.java

License:Apache License

private Watcher getConnectionWatcher() {
    return new Watcher() {
        @Override/*from  w ww  .  jav a2  s .  c om*/
        public void process(WatchedEvent event) {
            LOG.debug(String.format("Connection Event: %s", event.toString()));
        }
    };
}

From source file:com.continuuity.loom.common.zookeeper.LeaderElection.java

License:Apache License

private Watcher wrapWatcher(final Watcher watcher) {
    return new Watcher() {
        @Override/*from w  w  w  .  j a  va  2 s  . c om*/
        public void process(final WatchedEvent event) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    watcher.process(event);
                }
            });
        }
    };
}

From source file:com.continuuity.loom.common.zookeeper.lib.ZKInterProcessReentrantLock.java

License:Apache License

public void acquire() {
    if (isOwnerOfLock()) {
        return;//from  w  w  w .j  a  v a2s .  co  m
    }

    // The algo is the following:
    // 1) we add sequential ephemeral node
    // 2a) if added node is the first one in the list, we acquired the lock. Finish
    // 2b) if added node is not the first one, then add watch to the one before it to re-acquire when it is deleted.

    lockNode = Futures.getUnchecked(zkClient.create(lockPath, null, CreateMode.EPHEMERAL_SEQUENTIAL, true));
    NodeChildren nodeChildren = Futures.getUnchecked(zkClient.getChildren(path));
    List<String> children = nodeChildren.getChildren();
    Collections.sort(children);
    if (lockNode.equals(path + "/" + children.get(0))) {
        // we are the first to acquire the lock
        return;
    }

    final SettableFuture<Object> future = SettableFuture.create();
    boolean setWatcher = false;
    // add watch to the previous node
    Collections.reverse(children);
    for (String child : children) {
        child = path + "/" + child;
        if (child.compareTo(lockNode) < 0) {
            OperationFuture<Stat> exists = zkClient.exists(child, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getType() == Event.EventType.NodeDeleted) {
                        future.set(new Object());
                    }
                }
            });
            // if it was deleted before we managed to add watcher, we need to add watcher to the current previous, hence
            // continue looping
            if (Futures.getUnchecked(exists) != null) {
                setWatcher = true;
                break;
            }
        }
    }

    if (!setWatcher) {
        // we are owners of a lock, just return
        return;
    }

    // wait for lock to be released by previous owner
    Futures.getUnchecked(future);
}

From source file:com.continuuity.weave.internal.AbstractZKServiceController.java

License:Apache License

private void actOnExists(final String path, final Runnable action) {
    // Watch for node existence.
    final AtomicBoolean nodeExists = new AtomicBoolean(false);
    Futures.addCallback(zkClient.exists(path, new Watcher() {
        @Override// w  w  w  .  j a  v a  2  s.  c o m
        public void process(WatchedEvent event) {
            // When node is created, call the action.
            // Other event type would be handled by the action.
            if (event.getType() == Event.EventType.NodeCreated && nodeExists.compareAndSet(false, true)) {
                action.run();
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            if (result != null && nodeExists.compareAndSet(false, true)) {
                action.run();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("Failed in exists call to {}. Shutting down service.", path, t);
            forceShutDown();
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:com.continuuity.weave.internal.AbstractZKServiceController.java

License:Apache License

private void watchInstanceNode() {
    Futures.addCallback(zkClient.getData(getInstancePath(), new Watcher() {
        @Override/*from   w  ww.j  a v  a  2  s  . co m*/
        public void process(WatchedEvent event) {
            State state = state();
            if (state != State.NEW && state != State.STARTING && state != State.RUNNING) {
                // Ignore ZK node events when it is in stopping sequence.
                return;
            }
            switch (event.getType()) {
            case NodeDataChanged:
                watchInstanceNode();
                break;
            case NodeDeleted:
                // When the ephemeral node goes away, treat the remote service stopped.
                forceShutDown();
                break;
            default:
                LOG.info("Ignore ZK event for instance node: {}", event);
            }
        }
    }), instanceNodeDataCallback, Threads.SAME_THREAD_EXECUTOR);
}

From source file:com.continuuity.weave.internal.AbstractZKServiceController.java

License:Apache License

private void watchStateNode() {
    Futures.addCallback(zkClient.getData(getZKPath("state"), new Watcher() {
        @Override/*from w ww .  j  a va  2 s.  co m*/
        public void process(WatchedEvent event) {
            State state = state();
            if (state != State.NEW && state != State.STARTING && state != State.RUNNING) {
                // Ignore ZK node events when it is in stopping sequence.
                return;
            }
            switch (event.getType()) {
            case NodeDataChanged:
                watchStateNode();
                break;
            default:
                LOG.info("Ignore ZK event for state node: {}", event);
            }
        }
    }), stateNodeDataCallback, Threads.SAME_THREAD_EXECUTOR);
}

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

License:Open Source License

private void getBrokers() {
    final String idsPath = BROKERS_PATH + "/ids";

    Futures.addCallback(zkClient.getChildren(idsPath, new Watcher() {
        @Override/*from   www .  ja va  2 s . c o m*/
        public void process(WatchedEvent event) {
            getBrokers();
        }
    }), new ExistsOnFailureFutureCallback<NodeChildren>(idsPath, invokeGetBrokers) {
        @Override
        public void onSuccess(NodeChildren result) {
            Set<String> children = ImmutableSet.copyOf(result.getChildren());
            for (String child : children) {
                getBrokenData(idsPath + "/" + child, child);
            }
            // Remove all removed brokers
            removeDiff(children, brokers);
        }
    });
}