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:ch.usi.da.paxos.TopologyManager.java

License:Open Source License

@Override
public void process(WatchedEvent event) {
    try {// ww  w .j  a  v  a 2  s  . c  o  m
        if (event.getType() == EventType.NodeChildrenChanged) {
            if (event.getPath().startsWith(path + "/" + id_path)) {
                nodes.clear();
                List<String> l = zoo.getChildren(path + "/" + id_path, true);
                for (String s : l) {
                    nodes.add(Integer.valueOf(s));
                }
                notifyTopologyChanged();
            } else if (event.getPath().startsWith(path + "/" + acceptor_path)) {
                acceptors.clear();
                List<String> l = zoo.getChildren(path + "/" + acceptor_path, true);
                int min = nodeID + 1;
                int old_coordinator = coordinator;
                for (String s : l) {
                    int i = Integer.valueOf(s);
                    acceptors.add(i);
                    if (i < min) {
                        min = i;
                    }
                }
                coordinator = min;
                if (nodeID == min && old_coordinator != coordinator) {
                    notifyNewCoordinator();
                }
            } else if (event.getPath().startsWith(path + "/" + proposer_path)) {
                proposers.clear();
                List<String> l = zoo.getChildren(path + "/" + proposer_path, true);
                for (String s : l) {
                    proposers.add(Integer.valueOf(s));
                }
            } else if (event.getPath().startsWith(path + "/" + learner_path)) {
                learners.clear();
                List<String> l = zoo.getChildren(path + "/" + learner_path, true);
                for (String s : l) {
                    learners.add(Integer.valueOf(s));
                }
            }
        }
    } catch (KeeperException e) {
        logger.error(e);
    } catch (InterruptedException e) {
    }

}

From source file:ch.usi.da.smr.PartitionManager.java

License:Open Source License

@Override
public void process(WatchedEvent event) {
    if (event.getType() == EventType.NodeChildrenChanged && event.getPath().startsWith(path)) {
        readPartitions();//  ww  w.  j  ava 2s .co  m
    }
}

From source file:cn.lhfei.zookeeper.ConfigWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (event.getType() == EventType.NodeDataChanged) {
        try {/*from  w w w. ja va  2  s .co m*/
            displayConfig();
        } catch (InterruptedException e) {
            log.error("Interrupted. Exiting.");
            Thread.currentThread().interrupt();
        } catch (KeeperException e) {
            log.error("KeeperException: {}. Exiting.\n", e.getMessage(), e);
        }
    }
}

From source file:co.cask.cdap.common.zookeeper.store.ZKPropertyStore.java

License:Apache License

private void getDataAndWatch(final String name) {
    Futures.addCallback(zkClient.getData(getPath(name), new Watcher() {
        @Override//from  w  w  w  .jav  a  2 s  . c  om
        public void process(WatchedEvent event) {
            if (isClosed()) {
                return;
            }

            if (event.getType() == Event.EventType.NodeDeleted) {
                existsAndWatch(name);
            } else {
                getDataAndWatch(name);
            }
        }
    }), new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(NodeData result) {
            byte[] data = result.getData();
            if (data == null) {
                updateAndNotify(name, null);
            } else {
                try {
                    updateAndNotify(name, codec.decode(data));
                } catch (IOException e) {
                    LOG.error("Failed to decode property data for {}: {}", name, Bytes.toStringBinary(data), e);
                    notifyError(name, e);
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException.NoNodeException) {
                // If node not exists, watch for exists.
                existsAndWatch(name);
            } else {
                LOG.error("Failed to get property data for {}", name, t);
                notifyError(name, t);
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:co.cask.cdap.common.zookeeper.store.ZKPropertyStore.java

License:Apache License

private void existsAndWatch(final String name) {
    Futures.addCallback(zkClient.exists(getPath(name), new Watcher() {
        @Override//from www  .ja  va2s  . c  om
        public void process(WatchedEvent event) {
            if (isClosed()) {
                return;
            }

            // If the event is not node created, meaning the node was existed.
            // Hence getDataAndWatch should be handling that case already
            if (event.getType() == Event.EventType.NodeCreated) {
                getDataAndWatch(name);
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            // If the node exists, call getData. Otherwise, the watcher should handle the case when the node is created
            if (result != null) {
                getDataAndWatch(name);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("Failed to check exists for property data for {}", name, t);
            notifyError(name, t);
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:co.cask.cdap.route.store.ZKRouteStore.java

License:Apache License

private void existsAndWatch(final ProgramId serviceId, final SettableFuture<RouteConfig> oldSettableFuture) {
    Futures.addCallback(zkClient.exists(getZKPath(serviceId), new Watcher() {
        @Override//from   w w w .j a  v a  2s  .c  o  m
        public void process(WatchedEvent event) {
            // If service name doesn't exist in the map, then don't rewatch it.
            if (!routeConfigMap.containsKey(serviceId)) {
                return;
            }

            if (event.getType() == Event.EventType.NodeCreated) {
                getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture,
                        new ZKRouteWatcher(serviceId));
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(@Nullable Stat result) {
            if (result != null) {
                getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture,
                        new ZKRouteWatcher(serviceId));
            }
        }

        @Override
        public void onFailure(Throwable t) {
            routeConfigMap.remove(serviceId);
            LOG.debug("Failed to check exists for property data for {}", serviceId, t);
        }
    });
}

From source file:co.cask.tephra.zookeeper.TephraZKClientService.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    State state = state();/*from   w  ww .  j a va  2 s .co  m*/
    if (state == State.TERMINATED || state == State.FAILED) {
        return;
    }

    try {
        if (event.getState() == Event.KeeperState.SyncConnected && state == State.STARTING) {
            LOG.debug("Connected to ZooKeeper: {}", zkStr);
            notifyStarted();
            return;
        }
        if (event.getState() == Event.KeeperState.Expired) {
            LOG.info("ZooKeeper session expired: {}", zkStr);

            // When connection expired, simply reconnect again
            if (state != State.RUNNING) {
                return;
            }
            eventExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    // Only reconnect if the current state is running
                    if (state() != State.RUNNING) {
                        return;
                    }
                    try {
                        LOG.info("Reconnect to ZooKeeper due to expiration: {}", zkStr);
                        closeZooKeeper(zooKeeper.getAndSet(createZooKeeper()));
                    } catch (IOException e) {
                        notifyFailed(e);
                    }
                }
            });
        }
    } finally {
        if (event.getType() == Event.EventType.None) {
            for (Watcher connectionWatcher : connectionWatchers) {
                connectionWatcher.process(event);
            }
        }
    }
}

From source file:com.alibaba.jstorm.zk.Zookeeper.java

License:Apache License

/**
 * connect ZK, register Watch/unhandle Watch
 * /* www . j ava  2 s. c  om*/
 * @return
 */
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;
}

From source file:com.alibaba.otter.shared.arbitrate.impl.setl.zookeeper.monitor.StageMonitor.java

License:Apache License

/**
 * ?processId?/* www.j a  v  a  2s  .c  om*/
 */
private void syncStage(final Long processId) {
    // 1. ?pipelineId + processIdpath
    String path = null;
    try {
        path = StagePathUtils.getProcess(getPipelineId(), processId);
        // 2. ??process?
        IZkConnection connection = zookeeper.getConnection();
        // zkclient?zk?lock??watcher?zk?
        ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper();
        List<String> currentStages = orginZk.getChildren(path, new AsyncWatcher() {

            public void asyncProcess(WatchedEvent event) {
                MDC.put(ArbitrateConstants.splitPipelineLogFileKey, String.valueOf(getPipelineId()));
                if (isStop()) {
                    return;
                }

                if (event.getType() == EventType.NodeDeleted) {
                    processTermined(processId); // ?
                    return;
                }

                // session expired/connection losscase?watcher???watcher?watcher?
                boolean dataChanged = event.getType() == EventType.NodeDataChanged
                        || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated
                        || event.getType() == EventType.NodeChildrenChanged;
                if (dataChanged) {
                    // boolean reply = initStage(processId);
                    // if (reply == false) {// load???????
                    syncStage(processId);
                    // }
                }
            }
        });

        Collections.sort(currentStages, new StageComparator());
        List<String> lastStages = this.currentStages.get(processId);
        if (lastStages == null || !lastStages.equals(currentStages)) {
            initProcessStage(processId); // ?
        }

    } catch (NoNodeException e) {
        processTermined(processId); // ?
    } catch (KeeperException e) {
        syncStage(processId);
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:com.alibaba.otter.shared.common.utils.zookeeper.ZkClientx.java

License:Apache License

public void process(WatchedEvent event) {
    LOG.debug("Received event: " + event);
    _zookeeperEventThread = Thread.currentThread();

    boolean stateChanged = event.getPath() == null;
    boolean znodeChanged = event.getPath() != null;
    boolean dataChanged = event.getType() == EventType.NodeDataChanged
            || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated
            || event.getType() == EventType.NodeChildrenChanged;

    getEventLock().lock();/*from   w w  w  . j  av  a2 s.c om*/
    try {

        // We might have to install child change event listener if a new node was created
        if (getShutdownTrigger()) {
            LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath()
                    + "}' since shutdown triggered");
            return;
        }
        if (stateChanged) {
            processStateChanged(event);
        }
        if (dataChanged) {
            processDataOrChildChange(event);
        }
    } finally {
        if (stateChanged) {
            getEventLock().getStateChangedCondition().signalAll();

            // If the session expired we have to signal all conditions, because watches might have been removed and
            // there is no guarantee that those
            // conditions will be signaled at all after an Expired event
            // TODO PVo write a test for this
            if (event.getState() == KeeperState.Expired) {
                getEventLock().getZNodeEventCondition().signalAll();
                getEventLock().getDataChangedCondition().signalAll();
                // We also have to notify all listeners that something might have changed
                fireAllEvents();
            }
        }
        if (znodeChanged) {
            getEventLock().getZNodeEventCondition().signalAll();
        }
        if (dataChanged) {
            getEventLock().getDataChangedCondition().signalAll();
        }
        getEventLock().unlock();
        LOG.debug("Leaving process event");
    }
}