Example usage for org.apache.zookeeper WatchedEvent getType

List of usage examples for org.apache.zookeeper WatchedEvent getType

Introduction

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

Prototype

public EventType getType() 

Source Link

Usage

From source file:com.chinamobile.bcbsp.client.BSPJobClient.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (event.getType().toString().equals("NodeDeleted")) {
        LOG.info("Now the BspController will change");
        ensureFreshjJobSubmitClient();/*  w ww .  j  a v a 2s.  c  o m*/
        synchronized (mutex) {
            mutex.notify();
        }
    }
    // add for ZooKeeper connection Loss bug
    if (event.getState() == KeeperState.SyncConnected) {
        this.connectedLatch.countDown();
    }
}

From source file:com.chinamobile.bcbsp.workermanager.WorkerManager.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    LOG.info("now in process");
    LOG.info("event type is " + event.getType());
    try {//from  w  w w.  j  av  a 2 s.co  m
        if (event.getType().toString().equals("NodeDeleted")) {
            LOG.info("in NodeDeleted");
            if (bspzk != null) {
                if (bspzk.equaltoStat(Constants.BSPCONTROLLER_STANDBY_LEADER, true)) {
                    String standControllerAddr = getData(Constants.BSPCONTROLLER_LEADER);
                    InetSocketAddress newStandbyAddr = NetUtils.createSocketAddr(standControllerAddr);
                    if (!this.standbyControllerAddr.equals(newStandbyAddr)) {
                        this.bspControllerAddr = this.standbyControllerAddr;
                        this.standbyControllerAddr = newStandbyAddr;
                        this.controllerClient = (ControllerProtocol) RPC.getProxy(ControllerProtocol.class,
                                BSPRPCProtocolVersion.versionID, this.bspControllerAddr, conf);
                        this.standbyControllerClient = (ControllerProtocol) RPC.getProxy(
                                ControllerProtocol.class, BSPRPCProtocolVersion.versionID,
                                this.standbyControllerAddr, conf);
                    }
                    LOG.info("now the active is " + this.bspControllerAddr.toString() + "and the standby is "
                            + this.standbyControllerAddr.toString());
                }
            }
        } else if (event.getType().toString().equals("NodeDataChanged")) {
            // watch the standby
            bspzk.exists(Constants.BSPCONTROLLER_STANDBY_LEADER, true);
            // establish the communication link to standby bsp master
            this.standbyControllerClient = (ControllerProtocol) RPC.getProxy(ControllerProtocol.class,
                    BSPRPCProtocolVersion.versionID, this.standbyControllerAddr, conf);
            LOG.info("bspControllerAddr = " + bspControllerAddr + " standbyControllerAddr = "
                    + standbyControllerAddr);
            if (!this.standbyControllerClient.register(workerMangerStatus)) {
                LOG.error("There is a problem in establishing communication" + " link with BSPController");
                throw new IOException(
                        "There is a problem in establishing" + " communication link with BSPController.");
            } else {
                LOG.info("have registed to standby bsp master");
            }
        }
    } catch (Exception e) {
        LOG.error("problem happened when register to standby controller " + e.toString());
    }
}

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

License:Apache License

@Override
/**//www  . ja  v  a 2  s.  c  o  m
 * This is called whenever an event is seen on the ZK ensemble that we
 * have registered for. We care particularly about changes to the list of
 * configurations, made by some other peer.
 * 
 * TODO This is broken because the translation mechanism "buries" these configs. 
 */
public synchronized void process(WatchedEvent event) {
    if (client == null) {
        // This is the 'death-rattle' callback, made when we close the client.
        return;
    }
    LOG.debug("Saw ZooKeeper watch event " + event);
    if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
        if (event.getPath().equals(CFGS_PATH)) {
            try {
                LOG.info("Config was updated - reloading");
                loadConfigs(CFGS_PATH);
            } catch (IOException e) {
                LOG.error("IOException when reloading configs", e);
            }
        }
        if (event.getPath().equals(NODEMAPS_PATH)) {
            try {
                LOG.info("Nodemaps were updated - reloading");
                loadNodeMaps(NODEMAPS_PATH);
            } catch (IOException e) {
                LOG.error("IOException when reloading nodemaps", e);
            }
        }
        if (event.getPath().equals(CHOKEMAP_PATH)) {
            try {
                LOG.info("chokemaps were updated - reloading");
                loadChokeMap(CHOKEMAP_PATH);
            } catch (IOException e) {
                LOG.error("IOException when reloading ChokeMap", e);
            }
        }
    }
}

From source file:com.codefollower.lealone.zookeeper.ZooKeeperWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    switch (event.getType()) {
    case None: {/*  w  w  w.j a v a  2 s  .  c o  m*/
        connectionEvent(event);
        break;
    }

    case NodeCreated: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeCreated(event.getPath());
        }
        break;
    }

    case NodeDeleted: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeDeleted(event.getPath());
        }
        break;
    }

    case NodeDataChanged: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeDataChanged(event.getPath());
        }
        break;
    }

    case NodeChildrenChanged: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeChildrenChanged(event.getPath());
        }
        break;
    }
    }
}

From source file:com.codemacro.jcm.storage.ZookeeperStorageEngine.java

License:Apache License

public void process(WatchedEvent event) {
    if (event.getType() == Event.EventType.None) {
        switch (event.getState()) {
        case SyncConnected: // no matter session expired or not, we simply reload all
            for (ZookeeperPathWatcher w : watchers.values()) {
                w.onConnected();/*w  w w.  jav  a  2 s . co m*/
            }
            countDownLatch.countDown();
            break;
        case Disconnected: // zookeeper client will reconnect
            logger.warn("disconnected from zookeeper");
            break;
        // to test session expired, just close the laptop cover, making OS sleeping
        case Expired: // session expired by zookeeper server (after reconnected)
            logger.warn("session expired from zookeeper");
            for (ZookeeperPathWatcher w : watchers.values()) {
                w.onSessionExpired();
            }
            reconnect();
            break;
        default:
            break;
        }
    }
    String path = event.getPath();
    ZookeeperPathWatcher watcher = findWatcher(path);
    if (watcher == null) {
        return;
    }
    switch (event.getType()) {
    case NodeChildrenChanged:
        watcher.onListChanged();
        break;
    case NodeDataChanged:
        watcher.onChildData(path.substring(1 + path.lastIndexOf('/')));
    default:
        break;
    }
}

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

License:Apache License

public void acquire() {
    if (isOwnerOfLock()) {
        return;/*from www  .j av a 2  s . com*/
    }

    // 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  2s  .  com
        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// w ww.j a  v  a2  s .c o 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 w  w .  java 2s.c  o  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 getTopic(final String path, final String topic) {
    Futures.addCallback(zkClient.getChildren(path, new Watcher() {
        @Override//from   www .ja  va2  s .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)
        }
    });
}