Example usage for org.apache.zookeeper WatchedEvent getPath

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

Introduction

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

Prototype

public String getPath() 

Source Link

Usage

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();
    }/* ww w. j  ava2 s . c  om*/

    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;/*  w  w  w  .  j  a v  a 2  s . c om*/

    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;// w ww.  j  a v  a  2  s . c  o  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;/* ww  w.j a va  2s  . c om*/
    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 ww  w  . j  av  a2  s.c o  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();
        }
    }
}

From source file:org.apache.accumulo.server.master.LiveTServerSet.java

License:Apache License

@Override
public void process(WatchedEvent event) {

    // its important that these event are propagated by ZooCache, because this ensures when reading zoocache that is has already processed the event and cleared
    // relevant nodes before code below reads from zoocache

    if (event.getPath() != null) {
        if (event.getPath().endsWith(Constants.ZTSERVERS)) {
            scanServers();//w w  w .java2 s .  com
        } else if (event.getPath().contains(Constants.ZTSERVERS)) {
            int pos = event.getPath().lastIndexOf('/');

            // do only if ZTSERVER is parent
            if (pos >= 0 && event.getPath().substring(0, pos).endsWith(Constants.ZTSERVERS)) {

                String server = event.getPath().substring(pos + 1);

                final Set<TServerInstance> updates = new HashSet<>();
                final Set<TServerInstance> doomed = new HashSet<>();

                final String path = ZooUtil.getRoot(context.getInstance()) + Constants.ZTSERVERS;

                try {
                    checkServer(updates, doomed, path, server);
                    if (!doomed.isEmpty() || !updates.isEmpty())
                        this.cback.update(this, doomed, updates);
                } catch (Exception ex) {
                    log.error("Exception", ex);
                }
            }
        }
    }
}

From source file:org.apache.accumulo.server.security.delegation.ZooAuthenticationKeyWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (EventType.None == event.getType()) {
        switch (event.getState()) {
        case Disconnected: // Intentional fall through of case
        case Expired: // ZooReader is handling the Expiration of the original ZooKeeper object for us
            log.debug("ZooKeeper connection disconnected, clearing secret manager");
            secretManager.removeAllKeys();
            break;
        case SyncConnected:
            log.debug("ZooKeeper reconnected, updating secret manager");
            try {
                updateAuthKeys();/*from  w w  w  .ja  v a 2  s.  c  om*/
            } catch (KeeperException | InterruptedException e) {
                log.error("Failed to update secret manager after ZooKeeper reconnect");
            }
            break;
        default:
            log.warn("Unhandled: " + event);
        }

        // Nothing more to do for EventType.None
        return;
    }

    String path = event.getPath();
    if (null == path) {
        return;
    }

    if (!path.startsWith(baseNode)) {
        log.info("Ignoring event for path: {}", path);
        return;
    }

    try {
        if (path.equals(baseNode)) {
            processBaseNode(event);
        } else {
            processChildNode(event);
        }
    } catch (KeeperException | InterruptedException e) {
        log.error("Failed to communicate with ZooKeeper", e);
    }
}

From source file:org.apache.accumulo.server.security.delegation.ZooAuthenticationKeyWatcher.java

License:Apache License

/**
 * Process the {@link WatchedEvent} for the base znode that the {@link AuthenticationKey}s are stored in.
 *///ww  w  . ja va  2 s . com
void processBaseNode(WatchedEvent event) throws KeeperException, InterruptedException {
    switch (event.getType()) {
    case NodeDeleted:
        // The parent node was deleted, no children are possible, remove all keys
        log.debug("Parent ZNode was deleted, removing all AuthenticationKeys");
        secretManager.removeAllKeys();
        break;
    case None:
        // Not connected, don't care
        break;
    case NodeCreated: // intentional fall-through to NodeChildrenChanged
    case NodeChildrenChanged:
        // Process each child, and reset the watcher on the parent node. We know that the node exists
        updateAuthKeys(event.getPath());
        break;
    case NodeDataChanged:
        // The data on the parent changed. We aren't storing anything there so it's a noop
        break;
    default:
        log.warn("Unsupported event type: {}", event.getType());
        break;
    }
}

From source file:org.apache.accumulo.server.security.delegation.ZooAuthenticationKeyWatcher.java

License:Apache License

/**
 * Process the {@link WatchedEvent} for a node which represents an {@link AuthenticationKey}
 *///from ww  w.ja  v a2s. com
void processChildNode(WatchedEvent event) throws KeeperException, InterruptedException {
    final String path = event.getPath();
    switch (event.getType()) {
    case NodeDeleted:
        // Key expired
        if (null == path) {
            log.error("Got null path for NodeDeleted event");
            return;
        }

        // Pull off the base ZK path and the '/' separator
        String childName = path.substring(baseNode.length() + 1);
        secretManager.removeKey(Integer.parseInt(childName));
        break;
    case None:
        // Not connected, don't care. We'll update when we're reconnected
        break;
    case NodeCreated:
        // New key created
        if (null == path) {
            log.error("Got null path for NodeCreated event");
            return;
        }
        // Get the data and reset the watcher
        AuthenticationKey key = deserializeKey(zk.getData(path, this, null));
        log.debug("Adding AuthenticationKey with keyId {}", key.getKeyId());
        secretManager.addKey(key);
        break;
    case NodeDataChanged:
        // Key changed, could happen on restart after not running Accumulo.
        if (null == path) {
            log.error("Got null path for NodeDataChanged event");
            return;
        }
        // Get the data and reset the watcher
        AuthenticationKey newKey = deserializeKey(zk.getData(path, this, null));
        // Will overwrite the old key if one exists
        secretManager.addKey(newKey);
        break;
    case NodeChildrenChanged:
        // no children for the children..
        log.warn("Unexpected NodeChildrenChanged event for authentication key node {}", path);
        break;
    default:
        log.warn("Unsupported event type: {}", event.getType());
        break;
    }
}