Example usage for org.apache.zookeeper WatchedEvent getState

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

Introduction

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

Prototype

public KeeperState getState() 

Source Link

Usage

From source file:blazingcache.zookeeper.ZKCacheServerLocator.java

License:Apache License

@Override
protected ServerHostData getServer() {

    String leaderPath = basePath + "/leader";
    try {// ww w .  j  av a 2  s .c  o m
        byte[] data;
        if (ownedZk) {
            CountDownLatch connection = new CountDownLatch(1);
            try {
                LOGGER.finest("creating temp ZK client for discovery");
                ZooKeeper client = new ZooKeeper(zkAddress, zkSessiontimeout, new Watcher() {

                    @Override
                    public void process(WatchedEvent event) {
                        if (event.getState() == Event.KeeperState.SyncConnected
                                || event.getState() == Event.KeeperState.ConnectedReadOnly) {
                            connection.countDown();
                        }
                        LOGGER.severe("process ZK event " + event.getState() + " " + event.getType() + " "
                                + event.getPath());
                    }
                });
                try {
                    connection.await(connectTimeout, TimeUnit.MILLISECONDS);
                    LOGGER.finest("ZK client is " + client);
                    // se la connessione non sar stabilita in tempo o c' qualche problem troveremo un ConnectionLoss ad esempio                                        
                    data = client.getData(leaderPath, false, null);
                } finally {
                    client.close();
                }
            } catch (IOException err) {
                LOGGER.log(Level.SEVERE, "zookeeper client not available: " + err);
                return null;
            }

        } else {
            ZooKeeper client = zkSupplier.get();
            if (client == null) {
                LOGGER.log(Level.SEVERE, "zookeeper client available");
                return null;
            }
            data = client.getData(leaderPath, false, null);
        }
        lastKnownServer = ServerHostData.parseHostdata(data);
        return lastKnownServer;
    } catch (KeeperException.NoNodeException nobroker) {
        LOGGER.log(Level.SEVERE, "zookeeper client error", nobroker);
        return null;
    } catch (KeeperException | InterruptedException err) {
        LOGGER.log(Level.SEVERE, "zookeeper client error", err);
        return null;
    }
}

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

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (event.getState() == KeeperState.SyncConnected) {
        connectedSignal.countDown();/*from  w  w  w  . j a  va  2  s .co  m*/
    }
}

From source file:co.cask.tephra.distributed.ThriftTransactionServerTest.java

License:Apache License

private void expireZkSession(ZKClientService zkClientService) throws Exception {
    ZooKeeper zooKeeper = zkClientService.getZooKeeperSupplier().get();
    final SettableFuture<?> connectFuture = SettableFuture.create();
    Watcher watcher = new Watcher() {
        @Override/* w  ww  . j a v  a 2 s .c  o m*/
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                connectFuture.set(null);
            }
        }
    };

    // Create another Zookeeper session with the same sessionId so that the original one expires.
    final ZooKeeper dupZookeeper = new ZooKeeper(zkClientService.getConnectString(),
            zooKeeper.getSessionTimeout(), watcher, zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());
    connectFuture.get(30, TimeUnit.SECONDS);
    Assert.assertEquals("Failed to re-create current session", dupZookeeper.getState(),
            ZooKeeper.States.CONNECTED);
    dupZookeeper.close();
}

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

License:Apache License

@Override
public void process(WatchedEvent event) {
    State state = state();/*w  ww .j  a  va 2  s  . c  om*/
    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
 * //from ww w.  j a  v  a2s .  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.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();/*  ww w.j av  a  2  s.c o  m*/
    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");
    }
}

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

License:Apache License

private void processStateChanged(WatchedEvent event) {
    LOG.info("zookeeper state changed (" + event.getState() + ")");
    setCurrentState(event.getState());//from ww w .  ja  va  2  s  .co m
    if (getShutdownTrigger()) {
        return;
    }
    try {
        fireStateChangedEvent(event.getState());

        if (event.getState() == KeeperState.Expired) {
            reconnect();
            fireNewSessionEvents();
        }
    } catch (final Exception e) {
        throw new RuntimeException("Exception while restarting zk client", e);
    }
}

From source file:com.alibaba.wasp.zookeeper.ZooKeeperWatcher.java

License:Apache License

/**
 * Method called from ZooKeeper for events and connection status.
 * <p>//www  .  jav  a  2s . co m
 * Valid events are passed along to listeners. Connection status changes are
 * dealt with locally.
 */
@Override
public void process(WatchedEvent event) {
    LOG.debug(prefix("Received ZooKeeper Event, " + "type=" + event.getType() + ", " + "state="
            + event.getState() + ", " + "path=" + event.getPath()));

    switch (event.getType()) {

    // If event type is NONE, this is a connection status change
    case None: {
        connectionEvent(event);
        break;
    }

    // Otherwise pass along to the listeners

    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.alibaba.wasp.zookeeper.ZooKeeperWatcher.java

License:Apache License

/**
 * Called when there is a connection-related event via the Watcher callback.
 * <p>/*  w  w w.  ja  v  a 2 s.  c o m*/
 * If Disconnected or Expired, this should shutdown the cluster. But, since we
 * send a KeeperException.SessionExpiredException along with the abort call,
 * it's possible for the Abortable to catch it and try to create a new session
 * with ZooKeeper. This is what the client does in HCM.
 * <p>
 * @param event
 */
private void connectionEvent(WatchedEvent event) {
    switch (event.getState()) {
    case SyncConnected:
        // Now, this callback can be invoked before the this.zookeeper is set.
        // Wait a little while.
        long finished = System.currentTimeMillis()
                + this.conf.getLong("hbase.zookeeper.watcher.sync.connected.wait", 2000);
        while (System.currentTimeMillis() < finished) {
            Threads.sleep(1);
            if (this.recoverableZooKeeper != null)
                break;
        }
        if (this.recoverableZooKeeper == null) {
            LOG.error(
                    "ZK is null on connection event -- see stack trace "
                            + "for the stack trace when constructor was called on this zkw",
                    this.constructorCaller);
            throw new NullPointerException("ZK is null");
        }
        this.identifier = this.identifier + "-0x" + Long.toHexString(this.recoverableZooKeeper.getSessionId());
        // Update our identifier. Otherwise ignore.
        LOG.debug(this.identifier + " connected");
        break;

    case AuthFailed:
        if (ZKUtil.isSecureZooKeeper(this.conf)) {
            // We could not be authenticated, but clients should proceed anyway.
            // Only access to znodes that require SASL authentication will be
            // denied. The client may never need to access them.
            saslLatch.countDown();
        }
        break;

    // Abort the server if Disconnected or Expired
    case Disconnected:
        LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
        break;

    case Expired:
        if (ZKUtil.isSecureZooKeeper(this.conf)) {
            // We consider Expired equivalent to AuthFailed for this
            // connection. Authentication is never going to complete. The
            // client should proceed to do cleanup.
            saslLatch.countDown();
        }
        String msg = prefix(this.identifier + " received expired from " + "ZooKeeper, aborting");
        // TODO: One thought is to add call to ZooKeeperListener so say,
        // ZooKeeperNodeTracker can zero out its data values.
        if (this.abortable != null)
            this.abortable.abort(msg, new KeeperException.SessionExpiredException());
        break;

    default:
        throw new IllegalStateException("Received event is not valid.");
    }
}

From source file:com.andyadc.menagerie.DefaultZkSessionManager.java

License:Apache License

private void notifyListeners(WatchedEvent event) {
    notifyState(event.getState());
}