Example usage for org.apache.zookeeper KeeperException code

List of usage examples for org.apache.zookeeper KeeperException code

Introduction

In this page you can find the example usage for org.apache.zookeeper KeeperException code.

Prototype

Code code

To view the source code for org.apache.zookeeper KeeperException code.

Click Source Link

Usage

From source file:io.reign.data.ZkMultiMapData.java

License:Apache License

@Override
public synchronized List<String> keys() {
    List<String> keys = null;
    zkClientMultiDataUtil.lockForRead(readWriteLock, absoluteBasePath, this);
    try {//from   w w w.j  a  v a  2 s  . c om
        // if (readWriteLock == null) {
        // keys = zkClientMultiDataUtil.getChildListFromPathCache(absoluteBasePath, -1);
        // }

        if (keys == null) {
            // invalid or non-existent value in cache, so get direct
            Stat stat = new Stat();
            keys = zkClient.getChildren(absoluteBasePath, true, stat);
            // pathCache.put(absoluteBasePath, stat, null, keys);
        } else {
            logger.trace("Got from cache:  path={}; keys={}", absoluteBasePath, keys);
        }
    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NONODE) {
            if (logger.isDebugEnabled()) {
                logger.debug("Path does not exist for data update:  " + e + ":  path=" + absoluteBasePath);
            }
        } else {
            logger.error("" + e, e);
        }
    } catch (InterruptedException e) {
        logger.warn("Interrupted:  " + e, e);

    } finally {
        zkClientMultiDataUtil.unlockForRead(readWriteLock);
    }
    return keys != null ? keys : Collections.EMPTY_LIST;
}

From source file:io.reign.metrics.MetricsService.java

License:Apache License

MetricsData getMetricsFromDataNode(String clusterId, String serviceId, String dataNode) {
    PathScheme pathScheme = getContext().getPathScheme();
    String dataPath = null;/* w w w  . j  ava  2 s .  c o  m*/
    if (dataNode != null) {
        dataPath = pathScheme.getAbsolutePath(PathType.METRICS,
                pathScheme.joinTokens(clusterId, serviceId, dataNode));
    } else {
        dataPath = pathScheme.getAbsolutePath(PathType.METRICS, pathScheme.joinTokens(clusterId, serviceId));
    }
    byte[] bytes = null;
    try {
        Stat stat = new Stat();
        bytes = getContext().getZkClient().getData(dataPath, true, stat);

        logger.info("getMetricsFromDataNode():  dataPath={}; data={}", dataPath,
                new String(bytes).replace("\n", ""));

        MetricsData metricsData = JacksonUtil.getObjectMapper().readValue(bytes, MetricsData.class);
        metricsData.setLastUpdatedTimestamp(stat.getMtime());
        return metricsData;
    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NONODE) {
            return null;
        }
        logger.warn(
                "Error retrieving data node:  clusterId=" + clusterId + "; serviceId=" + serviceId
                        + "; dataPath=" + dataPath + "; dataAsString=" + (new String(bytes, UTF_8)) + ":  " + e,
                e);
        throw new ReignException("Error retrieving data node:  clusterId=" + clusterId + "; serviceId="
                + serviceId + "; dataPath=" + dataPath + "; dataAsString=" + (new String(bytes, UTF_8)), e);
    } catch (UnrecognizedPropertyException e) {
        logger.warn(
                "Error retrieving data node:  clusterId=" + clusterId + "; serviceId=" + serviceId
                        + "; dataPath=" + dataPath + "; dataAsString=" + (new String(bytes, UTF_8)) + ":  " + e,
                e);
        return null;
    } catch (Exception e) {
        logger.warn(
                "Error retrieving data node:  clusterId=" + clusterId + "; serviceId=" + serviceId
                        + "; dataPath=" + dataPath + "; dataAsString=" + (new String(bytes, UTF_8)) + ":  " + e,
                e);
        throw new ReignException("Error retrieving data node:  clusterId=" + clusterId + "; serviceId="
                + serviceId + "; dataPath=" + dataPath + "; dataAsString=" + (new String(bytes, UTF_8)), e);
    }
}

From source file:io.reign.metrics.MetricsService.java

License:Apache License

@Override
public ResponseMessage handleMessage(RequestMessage requestMessage) {
    ResponseMessage responseMessage = new SimpleResponseMessage();

    try {//from   w ww . ja  v  a 2s  .c o  m
        if (logger.isTraceEnabled()) {
            logger.trace("Received message:  nodeId={}; request='{}:{}'", requestMessage.getSenderId(),
                    requestMessage.getTargetService(), requestMessage.getBody());
        }

        /** preprocess request **/
        ParsedRequestMessage parsedRequestMessage = new ParsedRequestMessage(requestMessage);
        String resource = parsedRequestMessage.getResource();

        // strip beginning and ending slashes "/"
        boolean endsWithSlash = false;
        if (resource.startsWith("/")) {
            resource = resource.substring(1);
        }
        if (resource.endsWith("/")) {
            endsWithSlash = true;
            resource = resource.substring(0, resource.length() - 1);
        }

        /** get response **/
        if ("observe".equals(parsedRequestMessage.getMeta())) {
            responseMessage = new SimpleResponseMessage(ResponseStatus.OK);
            String[] tokens = getPathScheme().tokenizePath(resource);
            if (tokens.length == 2) {
                this.observe(tokens[0], tokens[1],
                        this.getClientObserver(parsedRequestMessage.getSenderId(), tokens[0], tokens[1], null));
            } else if (tokens.length == 3) {
                this.observe(tokens[0], tokens[1], this.getClientObserver(parsedRequestMessage.getSenderId(),
                        tokens[0], tokens[1], tokens[2]));
            } else {
                responseMessage.setComment("Observing not supported:  " + resource);
            }
        } else if ("observe-stop".equals(parsedRequestMessage.getMeta())) {
            responseMessage = new SimpleResponseMessage(ResponseStatus.OK);
            String absolutePath = getPathScheme().getAbsolutePath(PathType.METRICS, resource);
            getContext().getObserverManager().removeByOwnerId(parsedRequestMessage.getSenderId().toString(),
                    absolutePath);
        } else {
            if (resource.length() == 0) {
                // list available clusters
                String path = getContext().getPathScheme().getAbsolutePath(PathType.METRICS);
                List<String> clusterList = getContext().getZkClient().getChildren(path, false);
                responseMessage.setBody(clusterList);

            } else {
                String[] tokens = getPathScheme().tokenizePath(resource);
                // logger.debug("tokens.length={}", tokens.length);

                if (tokens.length == 1) {
                    // list available services
                    String path = getContext().getPathScheme().getAbsolutePath(PathType.METRICS, tokens[0]);
                    List<String> serviceList = getContext().getZkClient().getChildren(path, false);
                    responseMessage.setBody(serviceList);
                    if (serviceList == null) {
                        responseMessage.setComment("Not found:  " + resource);
                    }

                } else if (tokens.length == 2) {
                    if (endsWithSlash) {
                        // list available nodes for a given service
                        String path = getContext().getPathScheme().getAbsolutePath(PathType.METRICS, tokens[0],
                                tokens[1]);
                        List<String> nodeList = getContext().getZkClient().getChildren(path, false);

                        responseMessage.setBody(nodeList);
                        if (nodeList == null) {
                            responseMessage.setComment("Not found:  " + resource);
                        }
                    } else {
                        // get metrics data for service
                        MetricsData metricsData = getMetricsFromDataNode(tokens[0], tokens[1], null);
                        if (metricsData == null) {
                            responseMessage.setComment("Not found:  " + resource);
                        } else {
                            responseMessage.setBody(metricsData);
                        }
                    }

                } else if (tokens.length == 3) {
                    // get metrics data for single data node
                    MetricsData metricsData = getMetricsFromDataNode(tokens[0], tokens[1], tokens[2]);
                    if (metricsData == null) {
                        responseMessage.setComment("Not found:  " + resource);
                    } else {
                        responseMessage.setBody(metricsData);
                    }

                }
            }
        } // if observe

    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NONODE) {
            responseMessage.setBody(Collections.EMPTY_LIST);
        } else {
            responseMessage.setStatus(ResponseStatus.ERROR_UNEXPECTED, "" + e);
        }

    } catch (Exception e) {
        logger.error("" + e, e);
        responseMessage.setStatus(ResponseStatus.ERROR_UNEXPECTED, "" + e);

    }

    responseMessage.setId(requestMessage.getId());

    return responseMessage;

}

From source file:io.reign.metrics.MetricsService.java

License:Apache License

/**
 * Get metrics data for this service node (self) for current interval.
 *///  www.  j a va2  s .c o m
public MetricsData getMyMetrics(String clusterId, String serviceId) {
    String key = clusterId + "/" + serviceId + "/" + getContext().getZkNodeId().getPathToken();
    ExportMeta exportMeta = exportPathMap.get(key);
    if (exportMeta == null) {
        logger.trace(
                "MetricsData not found:  data has not been exported:  clusterId={}; serviceId={}; exportMeta={}",
                clusterId, serviceId, exportMeta);
        return null;
    }
    if (exportMeta.dataPath == null) {
        logger.trace(
                "MetricsData not found:  waiting for data to be reported in ZK:  clusterId={}; serviceId={}; exportMeta.dataPath={}",
                clusterId, serviceId, exportMeta.dataPath);
        synchronized (exportMeta) {
            try {
                exportMeta.wait();
            } catch (InterruptedException e) {
                logger.warn("Interrupted while waiting:  " + e, e);
            }
        }
    }

    try {
        logger.debug("Retrieving metrics:  path={}", exportMeta.dataPath);
        Stat stat = new Stat();
        byte[] bytes = getContext().getZkClient().getData(exportMeta.dataPath, true, stat);
        MetricsData metricsData = JacksonUtil.getObjectMapper().readValue(bytes, MetricsData.class);
        metricsData.setClusterId(clusterId);
        metricsData.setServiceId(serviceId);
        metricsData.setLastUpdatedTimestamp(stat.getMtime());
        return metricsData;
    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NONODE) {
            return null;
        }
        throw new ReignException(e);
    } catch (Exception e) {
        throw new ReignException(e);
    }

}

From source file:io.reign.ObserverManager.java

License:Apache License

public void put(String path, T observer) {
    String ownerId = observer.getOwnerId();
    Set<T> observerSet = getObserverSet(path, true);
    try {//from   www. ja  va 2 s . co m
        // decorate observer with data about the path so we can handle
        // notifications correctly
        byte[] data = zkClient.getData(path, true, new Stat());
        List<String> childList = zkClient.getChildren(path, true);

        observer.setPath(path);
        observer.setData(data);
        observer.setChildList(childList);
        observerSet.add(observer);

        // register with owner (so we can remove all later if a client
        // disconnects, etc.)
        if (ownerId != null) {
            Set<T> ownerObserverSet = getOwnerObserverSet(ownerId, true);
            ownerObserverSet.add(observer);
        }

        logger.info(
                "Added observer:  observer.hashCode()={}; observer.ownerId={}; path={}; pathObserverCount={}",
                new Object[] { observer.hashCode(), observer.getOwnerId(), path, observerSet.size() });
    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            // set up watch on that node
            try {
                observer.setPath(path);
                observer.setData(null);
                observer.setChildList(Collections.EMPTY_LIST);
                observerSet.add(observer);

                // register with owner (so we can remove all later if a
                // client disconnects, etc.)
                if (ownerId != null) {
                    Set<T> ownerObserverSet = getOwnerObserverSet(ownerId, true);
                    ownerObserverSet.add(observer);
                }

                zkClient.exists(path, true);

                logger.info(
                        "Added observer for nonexistent path:  observer.hashCode()={}; path={}; pathObserverCount={}",
                        new Object[] { observer.hashCode(), path, observerSet.size() });
            } catch (Exception e1) {
                logger.error("Unable to add observer:  path=" + path + "; observerType="
                        + observer.getClass().getSimpleName(), e);
            }

        } else {
            logger.error("Unable to add observer:  path=" + path + "; observerType="
                    + observer.getClass().getSimpleName(), e);
        }
    } catch (Exception e) {
        logger.error("Unable to add observer:  path=" + path + "; observerType="
                + observer.getClass().getSimpleName(), e);
    }

}

From source file:io.reign.ObserverManager.java

License:Apache License

@Override
public void nodeChildrenChanged(final WatchedEvent event) {
    delegatorExecutorService.submit(new Runnable() {
        public void run() {
            String path = event.getPath();
            logger.debug("Notifying ALL observers:  nodeChildrenChanged:  path={}", path);
            try {
                Set<T> observerSet = getObserverSet(path, false);
                if (observerSet.size() > 0) {
                    List<String> updatedChildList = null;
                    try {
                        updatedChildList = zkClient.getChildren(path, true);
                    } catch (KeeperException e) {
                        if (e.code() != KeeperException.Code.NONODE) {
                            throw e;
                        }/*from  ww  w  .ja  v a  2  s. co m*/
                    }
                    if (updatedChildList == null) {
                        updatedChildList = Collections.EMPTY_LIST;
                    }

                    for (final T observer : observerSet) {

                        logger.trace("Notifying observer:  observer.hashCode()={}", observer.hashCode());

                        synchronized (observer) {
                            final List<String> previousChildList = observer.getChildList();
                            boolean updatedValueDiffers = childListsDiffer(updatedChildList, previousChildList);

                            observer.setChildList(updatedChildList);

                            updateObserver(path, observer);

                            if (updatedValueDiffers) {
                                observer.nodeChildrenChanged(updatedChildList, previousChildList);
                            }
                        }
                    } // for

                    scheduleCheck(event);

                } // if observerSet > 0
            } catch (KeeperException e) {
                logger.warn("Unable to notify observers:  path=" + path, e);
            } catch (Exception e) {
                logger.warn("Unable to notify observers:  path=" + path, e);
            }
        }
    });

}

From source file:io.reign.presence.PresenceService.java

License:Apache License

public List<String> getClusters() {
    /** get node data from zk **/
    String path = getPathScheme().getAbsolutePath(PathType.PRESENCE);
    List<String> children = Collections.EMPTY_LIST;
    try {/*from w w w  .  j  ava 2  s. com*/
        Stat stat = new Stat();
        children = getZkClient().getChildren(path, true, stat);

        // getPathCache().put(path, stat, null, children);

    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            logger.warn("lookupClusters():  " + e + ":  node does not exist:  path={}", path);
        } else {
            logger.warn("lookupClusters():  " + e, e);
        }
        return Collections.EMPTY_LIST;
    } catch (InterruptedException e) {
        logger.warn("lookupClusters():  " + e, e);
        return Collections.EMPTY_LIST;
    }

    return children != null ? children : Collections.EMPTY_LIST;
}

From source file:io.reign.presence.PresenceService.java

License:Apache License

public List<String> getServices(String clusterId) {
    /** get node data from zk **/
    if (!getPathScheme().isValidToken(clusterId)) {
        throw new IllegalArgumentException("Invalid path token:  pathToken='" + clusterId + "'");
    }/*from w ww .j av a 2 s . c  o  m*/
    String path = getPathScheme().getAbsolutePath(PathType.PRESENCE, clusterId);
    List<String> children = Collections.EMPTY_LIST;
    try {
        Stat stat = new Stat();
        children = getZkClient().getChildren(path, true, stat);

    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            logger.warn("lookupServices():  " + e + ":  node does not exist:  path={}", path);
        } else {
            logger.warn("lookupServices():  " + e, e);
        }
        return Collections.EMPTY_LIST;
    } catch (InterruptedException e) {
        logger.warn("lookupServices():  " + e, e);
        return Collections.EMPTY_LIST;
    }

    return children;
}

From source file:io.reign.presence.PresenceService.java

License:Apache License

ServiceInfo getServiceInfo(String clusterId, String serviceId, PresenceObserver<ServiceInfo> observer,
        DataSerializer<Map<String, String>> nodeAttributeSerializer) {
    /** add observer if given **/
    if (observer != null) {
        this.observe(clusterId, serviceId, observer);
    }/*from   ww  w. j  a  v a2s. co  m*/

    /** get node data from zk **/
    String servicePath = getPathScheme().joinTokens(clusterId, serviceId);
    String path = getPathScheme().getAbsolutePath(PathType.PRESENCE, servicePath);

    boolean error = false;

    List<String> children = null;
    try {

        // get from ZK
        Stat stat = new Stat();
        children = getZkClient().getChildren(path, true, stat);

    } catch (KeeperException e) {
        error = true;

        if (e.code() == Code.NONODE) {
            // set up watch on that node
            try {
                getZkClient().exists(path, true);
            } catch (Exception e1) {
                logger.error("lookupServiceInfo():  error trying to watch node:  " + e1 + ":  path=" + path,
                        e1);
            }

            logger.debug(
                    "lookupServiceInfo():  error trying to fetch service info:  {}:  node does not exist:  path={}",
                    e.getMessage(), path);
        } else {
            logger.error("lookupServiceInfo():  error trying to fetch service info:  " + e, e);
        }

    } catch (Exception e) {
        logger.warn("lookupServiceInfo():  error trying to fetch service info:  " + e, e);
        error = true;
    }

    /** build service info **/
    ServiceInfo result = null;
    if (!error) {
        result = new StaticServiceInfo(clusterId, serviceId, children);
    }

    return result;

}

From source file:io.reign.presence.PresenceService.java

License:Apache License

NodeInfo getNodeInfo(String clusterId, String serviceId, String nodeId, PresenceObserver<NodeInfo> observer,
        DataSerializer<Map<String, String>> nodeAttributeSerializer) {
    /** get node data from zk **/
    String nodePath = getPathScheme().joinTokens(clusterId, serviceId, nodeId);
    String path = getPathScheme().getAbsolutePath(PathType.PRESENCE, nodePath);

    /** add observer if passed in **/
    if (observer != null) {
        this.observe(clusterId, serviceId, nodeId, observer);
    }//from w  ww.j  av a2s  .co  m

    /** fetch data **/
    boolean error = false;
    byte[] bytes = null;
    try {
        // populate from ZK
        Stat stat = new Stat();
        bytes = getZkClient().getData(path, true, stat);

    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            // set up watch on that node
            try {
                getZkClient().exists(path, true);
            } catch (Exception e1) {
                logger.error("lookupNodeInfo():  error trying to watch node:  " + e1 + ":  path=" + path, e1);
            }

            logger.debug(
                    "lookupNodeInfo():  error trying to fetch node info:  {}:  node does not exist:  path={}",
                    e.getMessage(), path);
        } else {
            logger.error("lookupNodeInfo():  error trying to fetch node info:  " + e, e);
        }
        error = true;
    } catch (Exception e) {
        logger.warn("lookupNodeInfo():  error trying to fetch node info:  " + e, e);
        error = true;
    }

    /** build node info **/
    NodeInfo result = null;
    if (!error) {
        try {
            result = new StaticNodeInfo(clusterId, serviceId,
                    getContext().getNodeIdFromZk(new ZkNodeId(nodeId, null)),
                    bytes != null ? nodeAttributeSerializer.deserialize(bytes) : Collections.EMPTY_MAP);
        } catch (Exception e) {
            throw new IllegalStateException(
                    "lookupNodeInfo():  error trying to fetch node info:  path=" + path + ":  " + e, e);
        }
    }

    return result;
}