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:net.sf.katta.zk.ZKClient.java

License:Apache License

@Override
public void process(WatchedEvent event) {

    // public void process(final WatcherEvent event) {
    // if (null == event.getPath()) {
    // // prohibit nullpointer (See ZOOKEEPER-77)
    // event.setPath("null");
    // }/*  ww  w .jav  a  2  s  .co  m*/
    boolean stateChanged = event.getState() == KeeperState.Disconnected
            || event.getState() == KeeperState.Expired;
    boolean dataChanged = event.getType() == Watcher.Event.EventType.NodeDataChanged
            || event.getType() == Watcher.Event.EventType.NodeChildrenChanged
            || event.getType() == Watcher.Event.EventType.NodeDeleted;
    try {
        getEventLock().lock();
        if (_shutdownTriggered) {
            LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath()
                    + "}' since shutdown triggered");
            return;
        }
        if (event.getState() == KeeperState.Expired) {
            processExpiration(event);
        }
        if (dataChanged) {
            processDataOrChildChange(event);
        }
    } finally {
        if (stateChanged) {
            getEventLock().getStateChangedCondition().signalAll();
        }
        if (dataChanged) {
            getEventLock().getDataChangedCondition().signalAll();
        }
        getEventLock().unlock();
    }
}

From source file:net.spy.memcached.CacheManager.java

License:Apache License

/***************************************************************************
 * We do process only child node change event ourselves, we just need to
 * forward them on.//from   w w w  .jav a2 s  . c o  m
 * 
 */
public void process(WatchedEvent event) {
    if (event.getType() == Event.EventType.None) {
        switch (event.getState()) {
        case SyncConnected:
            getLogger().info("Connected to Arcus admin. (%s@%s)", serviceCode, hostPort);
            zkInitLatch.countDown();
        }
    }

    if (cacheMonitor != null) {
        cacheMonitor.process(event);
    } else {
        getLogger().debug("cm is null, servicecode : %s, state:%s, type:%s", serviceCode, event.getState(),
                event.getType());
    }
}

From source file:net.spy.memcached.CacheMonitor.java

License:Apache License

/**
 * Processes every events from the ZooKeeper.
 *//*ww w .  java2s  .com*/
public void process(WatchedEvent event) {
    if (event.getType() == Event.EventType.None) {
        // Processes session events
        switch (event.getState()) {
        case SyncConnected:
            getLogger().warn("Reconnected to the Arcus admin. " + getInfo());
            return;
        case Disconnected:
            getLogger().warn("Disconnected from the Arcus admin. Trying to reconnect. " + getInfo());
            return;
        case Expired:
            // If the session was expired, just shutdown this client to be re-initiated.
            getLogger().warn("Session expired. Trying to reconnect to the Arcus admin." + getInfo());
            shutdown();
            return;
        }
    } else {
        // Set a new watch on the znode when there are any changes in it.
        if (event.getType() == Event.EventType.NodeChildrenChanged) {
            asyncGetCacheList();
        }
    }
}

From source file:org.apache.accumulo.fate.zookeeper.ZooLock.java

License:Apache License

private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
        throws KeeperException, InterruptedException {

    if (asyncLock == null) {
        throw new IllegalStateException("Called lockAsync() when asyncLock == null");
    }/*from   www. j  a  v a 2 s .co  m*/

    List<String> children = zooKeeper.getChildren(path);

    if (!children.contains(myLock)) {
        throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
    }

    Collections.sort(children);
    if (log.isTraceEnabled()) {
        log.trace("Candidate lock nodes");
        for (String child : children) {
            log.trace("- " + child);
        }
    }

    if (children.get(0).equals(myLock)) {
        log.trace("First candidate is my lock, acquiring");
        if (!watchingParent) {
            throw new IllegalStateException("Can not acquire lock, no longer watching parent : " + path);
        }
        this.lockWatcher = lw;
        this.lock = myLock;
        asyncLock = null;
        lockWasAcquired = true;
        lw.acquiredLock();
        return;
    }
    String prev = null;
    for (String child : children) {
        if (child.equals(myLock)) {
            break;
        }

        prev = child;
    }

    final String lockToWatch = path + "/" + prev;
    log.trace("Establishing watch on " + lockToWatch);
    Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {

        @Override
        public void process(WatchedEvent event) {
            if (log.isTraceEnabled()) {
                log.trace("Processing event:");
                log.trace("- type  " + event.getType());
                log.trace("- path  " + event.getPath());
                log.trace("- state " + event.getState());
            }
            boolean renew = true;
            if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
                log.trace("Detected deletion of " + lockToWatch + ", attempting to acquire lock");
                synchronized (ZooLock.this) {
                    try {
                        if (asyncLock != null) {
                            lockAsync(myLock, lw);
                        } else if (log.isTraceEnabled()) {
                            log.trace("While waiting for another lock " + lockToWatch + " " + myLock
                                    + " was deleted");
                        }
                    } catch (Exception e) {
                        if (lock == null) {
                            // have not acquired lock yet
                            lw.failedToAcquireLock(e);
                        }
                    }
                }
                renew = false;
            }

            if (event.getState() == KeeperState.Expired || event.getState() == KeeperState.Disconnected) {
                synchronized (ZooLock.this) {
                    if (lock == null) {
                        lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
                    }
                }
                renew = false;
            }
            if (renew) {
                log.trace("Renewing watch on " + lockToWatch);
                try {
                    Stat restat = zooKeeper.getStatus(lockToWatch, this);
                    if (restat == null) {
                        lockAsync(myLock, lw);
                    }
                } catch (KeeperException e) {
                    lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
                } catch (InterruptedException e) {
                    lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
                }
            }
        }

    });

    if (stat == null)
        lockAsync(myLock, lw);
}

From source file:org.apache.accumulo.fate.zookeeper.ZooLock.java

License:Apache License

public synchronized void lockAsync(final AsyncLockWatcher lw, byte data[]) {

    if (lockWatcher != null || lock != null || asyncLock != null) {
        throw new IllegalStateException();
    }//from   w  w w  .j  a va2s.  c  o  m

    lockWasAcquired = false;

    try {
        final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
        log.trace("Ephemeral node " + asyncLockPath + " created");
        Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {

            private void failedToAcquireLock() {
                lw.failedToAcquireLock(new Exception("Lock deleted before acquired"));
                asyncLock = null;
            }

            @Override
            public void process(WatchedEvent event) {
                synchronized (ZooLock.this) {
                    if (lock != null && event.getType() == EventType.NodeDeleted
                            && event.getPath().equals(path + "/" + lock)) {
                        lostLock(LockLossReason.LOCK_DELETED);
                    } else if (asyncLock != null && event.getType() == EventType.NodeDeleted
                            && event.getPath().equals(path + "/" + asyncLock)) {
                        failedToAcquireLock();
                    } else if (event.getState() != KeeperState.Disconnected
                            && event.getState() != KeeperState.Expired && (lock != null || asyncLock != null)) {
                        log.debug("Unexpected event watching lock node " + event + " " + asyncLockPath);
                        try {
                            Stat stat2 = zooKeeper.getStatus(asyncLockPath, this);
                            if (stat2 == null) {
                                if (lock != null)
                                    lostLock(LockLossReason.LOCK_DELETED);
                                else if (asyncLock != null)
                                    failedToAcquireLock();
                            }
                        } catch (Throwable e) {
                            lockWatcher.unableToMonitorLockNode(e);
                            log.error("Failed to stat lock node " + asyncLockPath, e);
                        }
                    }

                }
            }
        });

        if (stat == null) {
            lw.failedToAcquireLock(new Exception("Lock does not exist after create"));
            return;
        }

        asyncLock = asyncLockPath.substring(path.length() + 1);

        lockAsync(asyncLock, lw);

    } catch (KeeperException e) {
        lw.failedToAcquireLock(e);
    } catch (InterruptedException e) {
        lw.failedToAcquireLock(e);
    }
}

From source file:org.apache.accumulo.fate.zookeeper.ZooLock.java

License:Apache License

@Override
public synchronized void process(WatchedEvent event) {
    log.debug("event " + event.getPath() + " " + event.getType() + " " + event.getState());

    watchingParent = false;/*from   w  w  w  . ja  va2s.  com*/

    if (event.getState() == KeeperState.Expired && lock != null) {
        lostLock(LockLossReason.SESSION_EXPIRED);
    } else {

        try { // set the watch on the parent node again
            zooKeeper.getStatus(path, this);
            watchingParent = true;
        } catch (KeeperException.ConnectionLossException ex) {
            // we can't look at the lock because we aren't connected, but our session is still good
            log.warn("lost connection to zookeeper");
        } catch (Exception ex) {
            if (lock != null || asyncLock != null) {
                lockWatcher.unableToMonitorLockNode(ex);
                log.error("Error resetting watch on ZooLock " + lock == null ? asyncLock : lock + " " + event,
                        ex);
            }
        }

    }

}

From source file:org.apache.accumulo.server.conf.NamespaceConfWatcher.java

License:Apache License

static String toString(WatchedEvent event) {
    return new StringBuilder("{path=").append(event.getPath()).append(",state=").append(event.getState())
            .append(",type=").append(event.getType()).append("}").toString();
}

From source file:org.apache.accumulo.server.conf.NamespaceConfWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    String path = event.getPath();
    if (log.isTraceEnabled())
        log.trace("WatchedEvent : " + toString(event));

    String namespaceId = null;//from   w  w  w .j a  v  a 2 s . co  m
    String key = null;

    if (path != null) {
        if (path.startsWith(namespacesPrefix)) {
            namespaceId = path.substring(namespacesPrefixLength);
            if (namespaceId.contains("/")) {
                namespaceId = namespaceId.substring(0, namespaceId.indexOf('/'));
                if (path.startsWith(namespacesPrefix + namespaceId + Constants.ZNAMESPACE_CONF + "/"))
                    key = path.substring(
                            (namespacesPrefix + namespaceId + Constants.ZNAMESPACE_CONF + "/").length());
            }
        }

        if (namespaceId == null) {
            log.warn("Zookeeper told me about a path I was not watching: " + path + ", event "
                    + toString(event));
            return;
        }
    }

    switch (event.getType()) {
    case NodeDataChanged:
        if (log.isTraceEnabled())
            log.trace("EventNodeDataChanged " + event.getPath());
        if (key != null)
            scf.getNamespaceConfiguration(namespaceId).propertyChanged(key);
        break;
    case NodeChildrenChanged:
        scf.getNamespaceConfiguration(namespaceId).propertiesChanged();
        break;
    case NodeDeleted:
        if (key == null) {
            ServerConfigurationFactory.removeCachedNamespaceConfiguration(instance.getInstanceID(),
                    namespaceId);
        }
        break;
    case None:
        switch (event.getState()) {
        case Expired:
            ServerConfigurationFactory.expireAllTableObservers();
            break;
        case SyncConnected:
            break;
        case Disconnected:
            break;
        default:
            log.warn("EventNone event not handled " + toString(event));
        }
        break;
    case NodeCreated:
        switch (event.getState()) {
        case SyncConnected:
            break;
        default:
            log.warn("Event NodeCreated event not handled " + toString(event));
        }
        break;
    default:
        log.warn("Event not handled " + toString(event));
    }
}

From source file:org.apache.accumulo.server.conf.TableConfWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    String path = event.getPath();
    if (log.isTraceEnabled())
        log.trace("WatchedEvent : " + toString(event));

    String tableId = null;/*from   ww  w .j  av a 2s .  c o m*/
    String key = null;

    if (path != null) {
        if (path.startsWith(tablesPrefix)) {
            tableId = path.substring(tablesPrefix.length());
            if (tableId.contains("/")) {
                tableId = tableId.substring(0, tableId.indexOf('/'));
                if (path.startsWith(tablesPrefix + tableId + Constants.ZTABLE_CONF + "/"))
                    key = path.substring((tablesPrefix + tableId + Constants.ZTABLE_CONF + "/").length());
            }
        }

        if (tableId == null) {
            log.warn("Zookeeper told me about a path I was not watching: " + path + ", event "
                    + toString(event));
            return;
        }
    }

    switch (event.getType()) {
    case NodeDataChanged:
        if (log.isTraceEnabled())
            log.trace("EventNodeDataChanged " + event.getPath());
        if (key != null)
            scf.getTableConfiguration(tableId).propertyChanged(key);
        break;
    case NodeChildrenChanged:
        scf.getTableConfiguration(tableId).propertiesChanged();
        break;
    case NodeDeleted:
        if (key == null) {
            // only remove the AccumuloConfiguration object when a
            // table node is deleted, not when a tables property is
            // deleted.
            ServerConfigurationFactory.removeCachedTableConfiguration(instance.getInstanceID(), tableId);
        }
        break;
    case None:
        switch (event.getState()) {
        case Expired:
            ServerConfigurationFactory.expireAllTableObservers();
            break;
        case SyncConnected:
            break;
        case Disconnected:
            break;
        default:
            log.warn("EventNone event not handled " + toString(event));
        }
        break;
    case NodeCreated:
        switch (event.getState()) {
        case SyncConnected:
            break;
        default:
            log.warn("Event NodeCreated event not handled " + toString(event));
        }
        break;
    default:
        log.warn("Event not handled " + toString(event));
    }
}

From source file:org.apache.accumulo.server.logger.LogService.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    LOG.debug("event " + event.getPath() + " " + event.getType() + " " + event.getState());

    if (event.getState() == KeeperState.Expired) {
        LOG.warn("Logger lost zookeeper registration at " + event.getPath());
        service.stop();//from   w w w  .  jav  a2 s  .  co  m
    } else if (event.getType() == EventType.NodeDeleted) {
        LOG.info("Logger zookeeper entry lost " + event.getPath());
        String[] path = event.getPath().split("/");
        if (path[path.length - 1].equals(Constants.ZLOGGERS)
                && this.shutdownState == ShutdownState.REGISTERED) {
            LOG.fatal("Stopping server, zookeeper entry lost " + event.getPath());
            service.stop();
        }
    }
}