Example usage for org.apache.zookeeper KeeperException getMessage

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

Introduction

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

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:fr.eurecom.hybris.mds.ZkRmds.java

License:Apache License

@Override
public boolean tsWrite(String key, Metadata md, long zkVersion) throws HybrisException {

    String path = this.storageRoot + "/" + key;
    try {//w w w.  jav  a 2s.c  o m
        if (zkVersion == NONODE) {
            this.zkCli.create().forPath(path, md.serialize());
            logger.debug("ZNode {} created.", path);
            return false;
        } else {
            this.zkCli.setData().withVersion((int) zkVersion).forPath(path, md.serialize());
            logger.debug("ZNode {} modified.", path);
            return true;
        }
    } catch (KeeperException e) { // NONODE exception should not happen
        // since we set a tombstone value upon
        // deletion

        if (e.code() == KeeperException.Code.NODEEXISTS || // multiple
        // clients tried
        // to create
                e.code() == KeeperException.Code.BADVERSION) { // or modify
            // the same
            // znode
            // concurrently

            Stat stat = new Stat();
            byte[] newValue = null;
            try {
                newValue = this.zkCli.getData().storingStatIn(stat).forPath(path);
            } catch (Exception e1) {
                throw new HybrisException(e1);
            }

            Metadata newmd = new Metadata(newValue);
            if (md.getTs().isGreater(newmd.getTs())) {
                logger.debug("Found smaller version ({}) writing {}: retrying.", newmd.getTs(), key);
                return this.tsWrite(key, md, stat.getVersion());
            } else {
                logger.debug("Found greater version ({}) writing {}: overwritten.", newmd.getTs(), key);
                return false;
            }

        } else {
            logger.error("Could not write ZNode " + key);
            throw new HybrisException("Could not write the ZNode " + key, e);
        }

    } catch (Exception e) {
        logger.error("Could not write ZNode " + key, e);
        throw new HybrisException("Could not write ZNode " + key + ": " + e.getMessage(), e);
    }
}

From source file:fr.eurecom.hybris.mds.ZkRmds.java

License:Apache License

@Override
public boolean tsMultiWrite(LinkedHashMap<String, Metadata> mdMap, LinkedHashMap<String, Stat> statMap)
        throws HybrisException {

    try {/*  w w w.j  a v a2s  . c o  m*/
        CuratorTransaction curatorTransaction = this.zkCli.inTransaction();

        for (Entry<String, Metadata> entry : mdMap.entrySet()) {
            int ver = statMap.get(entry.getKey()).getVersion();
            if (ver == NONODE) {
                curatorTransaction = curatorTransaction.create()
                        .forPath(this.storageRoot + "/" + entry.getKey(), entry.getValue().serialize()).and();
            } else {
                curatorTransaction = curatorTransaction.setData().withVersion(ver)
                        .forPath(this.storageRoot + "/" + entry.getKey(), entry.getValue().serialize()).and();
            }
        }

        if (curatorTransaction instanceof CuratorTransactionFinal)
            ((CuratorTransactionFinal) curatorTransaction).commit();

        return true; // XXX

    } catch (KeeperException e) { // NONODE exception should not happen
        // since we set a tombstone value upon
        // deletion

        // XXX see if it is worth retrying

        logger.error("Could not perform transactional timestamped write.");
        throw new HybrisException("Could not perform transactional timestamped write: " + e.getMessage(), e);

    } catch (Exception e) {
        logger.error("Could not perform transactional timestamped write.", e);
        throw new HybrisException("Could not perform transactional timestamped write: " + e.getMessage(), e);
    }
}

From source file:fr.eurecom.hybris.mds.ZkRmds.java

License:Apache License

public Metadata tsRead(String key, Stat stat) throws HybrisException {

    String path = this.storageRoot + "/" + key;
    try {/*ww w .j av  a 2s.  co m*/
        if (quorumRead)
            this.zkCli.setData().forPath(this.storageRoot, new byte[] { (byte) 0x00 });
        else
            this.zkCli.sync().forPath(path);
        byte[] rawMd = this.zkCli.getData().storingStatIn(stat).forPath(path);
        return new Metadata(rawMd);
    } catch (KeeperException e) {

        if (e.code() == KeeperException.Code.NONODE)
            return null;
        else {
            logger.error("Could not read ZNode " + path, e);
            throw new HybrisException("Could not read the ZNode " + path, e);
        }

    } catch (Exception e) {
        logger.error("Could not read ZNode " + path, e);
        throw new HybrisException("Could not read the ZNode " + path + e.getMessage(), e);
    }
}

From source file:fr.eurecom.hybris.mds.ZkRmds.java

License:Apache License

public Metadata tsRead(String key, Stat stat, HybrisWatcher watcher) throws HybrisException {

    String path = this.storageRoot + "/" + key;
    try {/*www.  j  a  v a 2 s  .co  m*/
        if (quorumRead)
            this.zkCli.setData().forPath(this.storageRoot, new byte[] { (byte) 0x00 });
        else
            this.zkCli.sync().forPath(path);
        byte[] rawMd = this.zkCli.getData().storingStatIn(stat).usingWatcher(watcher).forPath(path);
        return new Metadata(rawMd);
    } catch (KeeperException e) {

        if (e.code() == KeeperException.Code.NONODE)
            return null;
        else {
            logger.error("Could not read ZNode " + path, e);
            throw new HybrisException("Could not read the ZNode " + path, e);
        }

    } catch (Exception e) {
        logger.error("Could not read ZNode " + path, e);
        throw new HybrisException("Could not read the ZNode " + path + e.getMessage(), e);
    }
}

From source file:io.reign.conf.ConfService.java

License:Apache License

<T> T getConfValue(String absolutePath, DataSerializer<T> confSerializer) {

    throwExceptionIfInvalidConfPath(absolutePath);

    byte[] bytes = null;
    T result = null;//w  ww. j a  v a  2 s  .  c om

    try {

        // not in cache, so load from ZK
        Stat stat = new Stat();
        bytes = getZkClient().getData(absolutePath, true, stat);

        result = bytes != null ? confSerializer.deserialize(bytes) : null;

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

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

    return result;
}

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   www. j a  v  a2 s.  c  om*/

    /** 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  a  va 2  s  . c o  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;
}

From source file:io.s4.comm.zk.ZkTaskManager.java

License:Open Source License

/**
 * This will block the process thread from starting the task, when it is
 * unblocked it will return the data stored in the task node. This data can
 * be used by the This call assumes that the tasks are already set up
 * //from  w ww  .jav a 2 s.  c o m
 * @return Object containing data related to the task
 */
@Override
public Object acquireTask(Map<String, String> customTaskData) {
    while (true) {
        synchronized (mutex) {
            try {
                Stat tExists = zk.exists(tasksListRoot, false);
                if (tExists == null) {
                    logger.error("Tasks znode:" + tasksListRoot + " not setup.Going to wait");
                    tExists = zk.exists(tasksListRoot, true);
                    if (tExists == null) {
                        mutex.wait();
                    }
                    continue;
                }
                Stat pExists = zk.exists(processListRoot, false);
                if (pExists == null) {
                    logger.error("Process root znode:" + processListRoot + " not setup.Going to wait");
                    pExists = zk.exists(processListRoot, true);
                    if (pExists == null) {
                        mutex.wait();
                    }
                    continue;
                }
                // setting watch true to tasks node will trigger call back
                // if there is any change to task node,
                // this is useful to add additional tasks
                List<String> tasks = zk.getChildren(tasksListRoot, true);
                List<String> processes = zk.getChildren(processListRoot, true);
                if (processes.size() < tasks.size()) {
                    ArrayList<String> tasksAvailable = new ArrayList<String>();
                    for (int i = 0; i < tasks.size(); i++) {
                        tasksAvailable.add("" + i);
                    }
                    if (processes != null) {
                        for (String s : processes) {
                            String taskId = s.split("-")[1];
                            tasksAvailable.remove(taskId);
                        }
                    }
                    // try pick up a random task
                    Random random = new Random();
                    int id = Integer.parseInt(tasksAvailable.get(random.nextInt(tasksAvailable.size())));
                    String pNode = processListRoot + "/" + "task-" + id;
                    String tNode = tasksListRoot + "/" + "task-" + id;
                    Stat pNodeStat = zk.exists(pNode, false);
                    if (pNodeStat == null) {
                        Stat tNodeStat = zk.exists(tNode, false);
                        byte[] bytes = zk.getData(tNode, false, tNodeStat);
                        Map<String, Object> map = (Map<String, Object>) JSONUtil
                                .getMapFromJson(new String(bytes));
                        // if(!map.containsKey("address")){
                        // map.put("address",
                        // InetAddress.getLocalHost().getHostName());
                        // }
                        if (customTaskData != null) {
                            for (String key : customTaskData.keySet()) {
                                if (!map.containsKey(key)) {
                                    map.put(key, customTaskData.get(key));
                                }
                            }

                        }
                        map.put("taskSize", "" + tasks.size());
                        map.put("tasksRootNode", tasksListRoot);
                        map.put("processRootNode", processListRoot);
                        String create = zk.create(pNode, JSONUtil.toJsonString(map).getBytes(),
                                Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                        logger.info("Created process Node:" + pNode + " :" + create);
                        return map;
                    }
                } else {
                    // all the tasks are taken up, will wait for the
                    logger.info("No task available to take up. Going to wait");
                    mutex.wait();
                }
            } catch (KeeperException e) {
                logger.info("Warn:mostly ignorable " + e.getMessage(), e);
            } catch (InterruptedException e) {
                logger.info("Warn:mostly ignorable " + e.getMessage(), e);
            }
        }
    }
}

From source file:io.tilt.minka.spectator.NodeCacheable.java

License:Apache License

/**
 * Create a child Znode (payload) within another parent (queue) Znode  
 *//*  w  ww. ja  v  a 2 s .c  om*/
private boolean createOrUpdatePath(final String completeName, final String clientName, final Object payload) {
    final CuratorFramework client = getClient();
    if (client == null) {
        logger.error("{}: ({}) Cannot use Distributed utilities before setting Zookeeper connection",
                getClass().getSimpleName(), getLogId());
        return false;
    }
    boolean result = false;
    try {
        //String regenPath = null;
        final byte[] bytes = SerializationUtils.serialize(new MessageMetadata(payload, clientName));
        try {
            acc += bytes.length;
            if (logger.isDebugEnabled()) {
                logger.debug("({}) BYTES SENT: {} (total = {})", getLogId(), bytes.length, acc);
            }
            final Collection<CuratorTransactionResult> res = createAndSetZNodeEnsuringPath(
                    CreateMode.PERSISTENT, completeName, 0, bytes);
            return checkTxGeneratedPath(res) != null;
        } catch (KeeperException e) {
            logger.error("{}: ({}) Unexpected while posting message: {}", getClass().getSimpleName(),
                    getLogId(), completeName, e);
            return false;
        }
    } catch (Exception e) {
        if (isStarted() && isConnected()) {
            logger.error("{}: ({}) Unexpected while posting message: {}", getClass().getSimpleName(),
                    getLogId(), completeName, e);
        } else {
            logger.error("{}: ({}) Zookeeper Disconnection: while posting message: {}",
                    getClass().getSimpleName(), getLogId(), completeName, e.getMessage());
        }
    }
    return result;
}

From source file:io.tilt.minka.spectator.NodeCacheable.java

License:Apache License

private Collection<CuratorTransactionResult> createZNode(final CreateMode mode, final String path,
        final byte[] bytes) throws Exception {
    try {//from   w  ww.  ja v a 2 s  . co m
        logger.info("{}: ({}) Changing path: {}", getClass().getSimpleName(), getLogId(), path);
        return getClient().inTransaction().setData().forPath(path, bytes).and().commit();
    } catch (KeeperException ke) {
        if (ke.code() == KeeperException.Code.NONODE) {
            logger.info("{}: ({}) Creating parent path for first time: {} because: {}",
                    getClass().getSimpleName(), getLogId(), path, ke.getMessage());
            return getClient().inTransaction().create().withMode(mode).forPath(path, bytes).and().commit();
        } else {
            logger.error("{}: ({}) Unexpected creating node: {}", getClass().getSimpleName(), getLogId(), path);
            throw ke;
        }
    }
}