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.twitter.finagle.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Returns the current active ZK connection or establishes a new one if none has yet been
 * established or a previous connection was disconnected or had its session time out.  This
 * method will attempt to re-use sessions when possible.
 *
 * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK
 *     cluster to be established; 0 to wait forever
 * @return a connected ZooKeeper client/*  ww w  .j a v a2  s  . c o m*/
 * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster
 * @throws InterruptedException if interrupted while waiting for a connection to be established
 * @throws TimeoutException if a connection could not be established within the configured
 *     session timeout
 */
public synchronized ZooKeeper get(Duration connectionTimeout)
        throws ZooKeeperConnectionException, InterruptedException, TimeoutException {

    if (zooKeeper == null) {
        final CountDownLatch connected = new CountDownLatch(1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                switch (event.getType()) {
                // Guard the None type since this watch may be used as the default watch on calls by
                // the client outside our control.
                case None:
                    switch (event.getState()) {
                    case Expired:
                        LOG.info("Zookeeper session expired. Event: " + event);
                        close();
                        break;
                    case SyncConnected:
                        connected.countDown();
                        break;
                    default:
                        break; // nop
                    }
                    break;
                default:
                    break; // nop
                }

                eventQueue.offer(event);
            }
        };

        try {
            zooKeeper = (sessionState != null)
                    ? new ZooKeeper(connectString, sessionTimeoutMs, watcher, sessionState.sessionId,
                            sessionState.sessionPasswd)
                    : new ZooKeeper(connectString, sessionTimeoutMs, watcher);
        } catch (IOException e) {
            throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e);
        }

        if (connectionTimeout.inMillis() > 0) {
            if (!connected.await(connectionTimeout.inMillis(), TimeUnit.MILLISECONDS)) {
                close();
                throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout);
            }
        } else {
            try {
                connected.await();
            } catch (InterruptedException ex) {
                LOG.info("Interrupted while waiting to connect to zooKeeper");
                close();
                throw ex;
            }
        }
        credentials.authenticate(zooKeeper);

        sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());
    }
    return zooKeeper;
}

From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Clients that need to re-establish state after session expiration can register an
 * {@code onExpired} command to execute.
 *
 * @param onExpired the {@code Runnable} to register
 * @return the new {@link Watcher} which can later be passed to {@link #unregister} for
 *     removal./* w w w  . jav  a2  s.c  om*/
 */
public Watcher registerExpirationHandler(final Runnable onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                onExpired.run();
            }
        }
    };
    register(watcher);
    return watcher;
}

From source file:com.twitter.heron.statemgr.zookeeper.ZkWatcherCallback.java

License:Open Source License

public static Watcher makeZkWatcher(final WatchCallback watcher) {
    return watcher == null ? null : new Watcher() {
        @Override//  w  ww. j ava2  s .  c o  m
        public void process(WatchedEvent watchedEvent) {
            WatchCallback.WatchEventType watchEventType;
            switch (watchedEvent.getType()) {
            case None:
                watchEventType = WatchCallback.WatchEventType.None;
                break;
            case NodeCreated:
                watchEventType = WatchCallback.WatchEventType.NodeCreated;
                break;
            case NodeDeleted:
                watchEventType = WatchCallback.WatchEventType.NodeDeleted;
                break;
            case NodeDataChanged:
                watchEventType = WatchCallback.WatchEventType.NodeDataChanged;
                break;
            case NodeChildrenChanged:
                watchEventType = WatchCallback.WatchEventType.NodeChildrenChanged;
                break;

            default:
                throw new RuntimeException("Invalid integer value for conversion to EventType");
            }
            watcher.processWatch(watchedEvent.getPath(), watchEventType);
        }
    };
}

From source file:com.vmware.photon.controller.common.zookeeper.DataDictionary.java

License:Open Source License

/**
 * Reads and returns ZK node {basePath}/{key} value, optionally setting up a one-time callback for the data change.
 *
 * @param key             Key to read/*from w  w  w.jav a 2s. c  o  m*/
 * @param changeListener  Callback that gets called when node data has changed. Will only be called once
 * @param notifyWhenAdded If true, watch will be set if the node is missing and fire once it's created
 * @return Node data or null if key doesn't exist yet
 * @throws Exception
 */
public byte[] read(final String key, final ChangeListener changeListener, boolean notifyWhenAdded)
        throws Exception {
    final String nodePath = ZKPaths.makePath(basePath, key);

    CuratorWatcher watcher = new CuratorWatcher() {
        @Override
        public void process(final WatchedEvent event) throws Exception {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    if (event.getType() == Watcher.Event.EventType.NodeDataChanged) {
                        changeListener.onDataChanged(key);
                    } else if (event.getType() == Watcher.Event.EventType.NodeDeleted) {
                        changeListener.onKeyRemoved(key);
                    } else if (event.getType() == Watcher.Event.EventType.NodeCreated) {
                        changeListener.onKeyAdded(key);
                    }
                }
            });
        }
    };

    try {
        if (changeListener != null) {
            return zkClient.getData().usingWatcher(watcher).forPath(nodePath);
        } else {
            return zkClient.getData().forPath(nodePath);
        }
    } catch (KeeperException.NoNodeException e) {
        if (changeListener != null && notifyWhenAdded) {
            zkClient.checkExists().usingWatcher(watcher).forPath(nodePath);
        }
        return null;
    }
}

From source file:com.yahoo.pasc.paxos.Barrier.java

License:Open Source License

@Override
public void process(org.apache.zookeeper.WatchedEvent event) {
    if (event.getType().equals(EventType.NodeChildrenChanged)
            || event.getType().equals(EventType.NodeCreated)) {
        synchronized (mutex) {
            mutex.notify();//from  w  w w.jav  a  2 s . c o m
        }
    }
}

From source file:com.yahoo.pulsar.broker.loadbalance.LeaderElectionService.java

License:Apache License

/**
 * We try to get the data in the ELECTION_ROOT node. If the node is present (i.e. leader is present), we store it in
 * the currentLeader and keep a watch on the election node. If we lose the leader, then watch gets triggered and we
 * do the election again. If the node does not exist while getting the data, we get NoNodeException. This means,
 * there is no leader and we create the node at ELECTION_ROOT and write the leader broker's service URL in the node.
 * Once the leader is known, we call the listener method so that leader can take further actions.
 *//*w  ww . j a v  a 2 s  .  c om*/
private void elect() {
    try {
        byte[] data = zkClient.getData(ELECTION_ROOT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                log.warn("Type of the event is [{}] and path is [{}]", event.getType(), event.getPath());
                switch (event.getType()) {
                case NodeDeleted:
                    log.warn("Election node {} is deleted, attempting re-election...", event.getPath());
                    if (event.getPath().equals(ELECTION_ROOT)) {
                        log.info("This should call elect again...");
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                // If the node is deleted, attempt the re-election
                                log.info("Broker [{}] is calling re-election from the thread",
                                        pulsar.getWebServiceAddress());
                                elect();
                            }
                        });
                    }
                    break;

                default:
                    log.warn("Got something wrong on watch: {}", event);
                    break;
                }
            }
        }, null);

        LeaderBroker leaderBroker = jsonMapper.readValue(data, LeaderBroker.class);
        currentLeader.set(leaderBroker);
        isLeader.set(false);
        leaderListener.brokerIsAFollowerNow();

        // If broker comes here it is a follower. Do nothing, wait for the watch to trigger
        log.info("Broker [{}] is the follower now. Waiting for the watch to trigger...",
                pulsar.getWebServiceAddress());

    } catch (NoNodeException nne) {
        // There's no leader yet... try to become the leader
        try {
            // Create the root node and add current broker's URL as its contents
            LeaderBroker leaderBroker = new LeaderBroker(pulsar.getWebServiceAddress());
            ZkUtils.createFullPathOptimistic(pulsar.getLocalZkCache().getZooKeeper(), ELECTION_ROOT,
                    jsonMapper.writeValueAsBytes(leaderBroker), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

            // Update the current leader and set the flag to true
            currentLeader.set(new LeaderBroker(leaderBroker.getServiceUrl()));
            isLeader.set(true);

            // Notify the listener that this broker is now the leader so that it can collect usage and start load
            // manager.
            log.info("Broker [{}] is the leader now, notifying the listener...", pulsar.getWebServiceAddress());
            leaderListener.brokerIsTheLeaderNow();
        } catch (NodeExistsException nee) {
            // Re-elect the new leader
            log.warn(
                    "Got exception [{}] while creating election node because it already exists. Attempting re-election...",
                    nee.getMessage());
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    elect();
                }
            });
        } catch (Exception e) {
            // Kill the broker because this broker's session with zookeeper might be stale. Killing the broker will
            // make sure that we get the fresh zookeeper session.
            log.error("Got exception [{}] while creating the election node", e.getMessage());
            pulsar.getShutdownService().shutdown(-1);
        }

    } catch (Exception e) {
        // Kill the broker
        log.error("Could not get the content of [{}], got exception [{}]. Shutting down the broker...",
                ELECTION_ROOT, e);
        pulsar.getShutdownService().shutdown(-1);
    }
}

From source file:com.yahoo.pulsar.zookeeper.GlobalZooKeeperCache.java

License:Apache License

@Override
public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) {
    synchronized (this) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("[{}] Got Global ZooKeeper WatchdEvent: EventType: {}, KeeperState: {}, path: {}",
                    this.hashCode(), event.getType(), event.getState(), event.getPath());
        }//from   w  w w .  j  av  a  2 s  .  c o  m
        if (event.getType() == Event.EventType.None) {
            switch (event.getState()) {
            case Expired:
                // in case of expired, the zkSession is no longer good for sure.
                // We need to restart the session immediately.
                // cancel any timer event since it is already bad
                ZooKeeper oldSession = this.zkSession.getAndSet(null);
                LOG.warn("Global ZK session lost. Triggering reconnection {}", oldSession);
                safeCloseZkSession(oldSession);
                asyncRestartZooKeeperSession();
                return;
            case SyncConnected:
            case ConnectedReadOnly:
                checkNotNull(zkSession.get());
                LOG.info("Global ZK session {} restored connection.", zkSession.get());

                //
                dataCache.synchronous().invalidateAll();
                childrenCache.invalidateAll();
                return;
            default:
                break;
            }
        }
    }

    // Other types of events
    super.process(event, updater);

}

From source file:com.yahoo.pulsar.zookeeper.LocalZooKeeperCache.java

License:Apache License

@Override
public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Got Local ZooKeeper WatchedEvent: EventType: {}, KeeperState: {}, Path: {}", event.getType(),
                event.getState(), event.getPath());
    }/*from w w  w.  j a va2  s .  c  om*/
    if (event.getType() == Event.EventType.None) {
        switch (event.getState()) {
        case Expired:
            // in case of expired, the zkSession is no longer good
            LOG.warn("Lost connection from local ZK. Invalidating the whole cache.");
            dataCache.synchronous().invalidateAll();
            childrenCache.invalidateAll();
            return;
        default:
            break;
        }
    }
    super.process(event, updater);
}

From source file:com.yahoo.pulsar.zookeeper.ZooKeeperSessionWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    Watcher.Event.EventType eventType = event.getType();
    Watcher.Event.KeeperState eventState = event.getState();

    LOG.info("Received zookeeper notification, eventType={}, eventState={}", eventType, eventState);

    switch (eventType) {
    case None:/*  ww  w  . j a va 2 s .c om*/
        if (eventState == Watcher.Event.KeeperState.Expired) {
            LOG.error("ZooKeeper session already expired, invoking shutdown");
            close();
            shuttingDown = true;
            shutdownService.shutdown(-1);
        }
        break;
    default:
        break;
    }

}

From source file:com.yihaodian.architecture.zkclient.ZkClient.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 a v  a 2s.co 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");
    }
}