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:org.apache.hadoop.hdfs.notifier.server.ServerLogReaderAvatar.java

License:Apache License

/**
 * Detect the primary node and the current Journal Manager;
 * @throws IOException//from w ww  .  j  a va2 s . co  m
 */
protected void detectJournalManager() throws IOException {
    int failures = 0;
    do {
        try {
            Stat stat = new Stat();
            String primaryAddr = zk.getPrimaryAvatarAddress(logicalName, stat, true, true);
            if (primaryAddr == null || primaryAddr.trim().isEmpty()) {
                primaryURI = null;
                remoteJournalManager = null;
                LOG.warn("Failover detected, wait for it to finish...");
                failures = 0;
                sleep(FAILOVER_RETRY_SLEEP);
                continue;
            }

            primaryURI = addrToURI(primaryAddr);

            LOG.info("Read primary URI from zk: " + primaryURI);
            if (primaryURI.equals(avatarZeroURI)) {
                remoteJournalManager = remoteJournalManagerZero;
            } else if (primaryURI.equals(avatarOneURI)) {
                remoteJournalManager = remoteJournalManagerOne;
            } else {
                LOG.warn("Invalid primaryURI: " + primaryURI);
                primaryURI = null;
                remoteJournalManager = null;
                failures = 0;
                sleep(FAILOVER_RETRY_SLEEP);
            }

        } catch (KeeperException kex) {
            if (KeeperException.Code.CONNECTIONLOSS == kex.code()
                    && failures < AvatarZooKeeperClient.ZK_CONNECTION_RETRIES) {
                failures++;
                // This means there was a failure connecting to zookeeper
                // we should retry since some nodes might be down.
                sleep(FAILOVER_RETRY_SLEEP);
                continue;
            }
            throwIOException(kex.getMessage(), kex);
        } catch (InterruptedException e) {
            throwIOException(e.getMessage(), e);
        } catch (URISyntaxException e) {
            throwIOException(e.getMessage(), e);
        }
    } while (remoteJournalManager == null);
}

From source file:org.apache.manifoldcf.core.lockmanager.ZooKeeperConnection.java

License:Apache License

/** Handle keeper exceptions that may involve ephemeral node creation.
*/// w  w  w . j  a  v  a2s  .co  m
protected void handleEphemeralNodeKeeperException(KeeperException e, boolean recreate)
        throws ManifoldCFException, InterruptedException {
    if (e instanceof KeeperException.ConnectionLossException
            || e instanceof KeeperException.SessionExpiredException) {
        while (true) {
            try {
                // Close the handle, open a new one
                lockNode = null;
                if (!recreate) {
                    nodePath = null;
                    nodeData = null;
                }
                zookeeper.close();
                createSession();
                // Lock is lost, but we can (and should) recreate the ephemeral nodes
                if (nodePath != null) {
                    zookeeper.create(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                }
                break;
            } catch (KeeperException e2) {
                if (!(e2 instanceof KeeperException.ConnectionLossException)
                        && !(e2 instanceof KeeperException.SessionExpiredException))
                    throw new ManifoldCFException(e2.getMessage(), e2);
            }
        }
    } else {
        // If nothing we know how to deal with, throw.
        throw new ManifoldCFException(e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.core.lockmanager.ZooKeeperConnection.java

License:Apache License

/** Handle keeper exceptions that don't involve ephemeral node creation.
*//*from   w  w w  .j  a v a2s . com*/
protected void handleKeeperException(KeeperException e, boolean recreate)
        throws ManifoldCFException, InterruptedException {
    if (e instanceof KeeperException.ConnectionLossException) {
        // Retry if connection loss
        ManifoldCF.sleep(100L);
    } else if (e instanceof KeeperException.SessionExpiredException) {
        while (true) {
            try {
                // Close the handle, open a new one
                lockNode = null;
                if (!recreate) {
                    nodePath = null;
                    nodeData = null;
                }
                zookeeper.close();
                createSession();
                // Lock is lost, but we can (and should) recreate the ephemeral nodes
                if (nodePath != null) {
                    zookeeper.create(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                }
                break;
            } catch (KeeperException e2) {
                if (!(e2 instanceof KeeperException.ConnectionLossException)
                        && !(e2 instanceof KeeperException.SessionExpiredException))
                    throw new ManifoldCFException(e2.getMessage(), e2);
            }
        }
    } else {
        // If nothing we know how to deal with, throw.
        throw new ManifoldCFException(e.getMessage(), e);
    }
}

From source file:org.apache.marmotta.platform.zookeeper.services.ZookeeperServiceImpl.java

License:Apache License

public void initialise(@Observes ConfigurationServiceInitEvent event) throws IOException, InterruptedException {
    log.warn("Activating Marmotta Zookeeper Bridge");

    //read configuration
    final String connectionString = configurationService.getContextParam(ZK_SERVER);

    if (connectionString != null) {

        log.info(" - connection string: {}", connectionString);

        this.properties = new Properties();
        File nkProperties = new File(configurationService.getHome() + File.separator + "nodekeeper.properties");
        if (nkProperties.exists()) {
            properties.load(new FileInputStream(nkProperties));
        }/*from ww w. j  a v a2s . c  om*/

        // get instance id (if not configured), first try from context parameters, if not given create random
        if (StringUtils.isBlank(configurationService.getStringConfiguration(ZK_INSTANCE))) {
            String instanceId;
            if (StringUtils.isBlank(configurationService.getContextParam(ZK_INSTANCE))) {
                instanceId = UUID.randomUUID().toString();
            } else {
                instanceId = configurationService.getContextParam(ZK_INSTANCE);
            }

            configurationService.setConfiguration(ZK_INSTANCE, instanceId);
        }

        // get cluster name (if not configured), first try from context parameters, if not given use "default"
        if (StringUtils.isBlank(configurationService.getStringConfiguration(ZK_CLUSTER))) {
            String clusterId;
            if (StringUtils.isBlank(configurationService.getContextParam(ZK_CLUSTER))) {
                clusterId = "default";
            } else {
                clusterId = configurationService.getContextParam(ZK_CLUSTER);
            }

            configurationService.setConfiguration(ZK_CLUSTER, clusterId);
        }

        log.info(" - initialize nodekeeper connection for instance {} (cluster {})",
                configurationService.getStringConfiguration(ZK_INSTANCE),
                configurationService.getStringConfiguration(ZK_CLUSTER));

        try {
            nodeKeeper = new NodeKeeper(connectionString,
                    configurationService.getIntConfiguration(ZK_TIMEOUT, 60000), properties, null);

            initZooKeeper();

            String uuid = configurationService.getStringConfiguration(ZK_INSTANCE,
                    UUID.randomUUID().toString());
            String cluster = configurationService.getStringConfiguration(ZK_CLUSTER, "default");

            ConfigurationListener listener = new ConfigurationListener(configurationService, nodeKeeper);

            nodeKeeper.addListener("/marmotta/config/[^/]+", listener);
            nodeKeeper.addListener(String.format("/marmotta/clusters/%s/config/[^/]+", cluster), listener);
            nodeKeeper.addListener(
                    String.format("/marmotta/clusters/%s/instances/%s/config/[^/]+", cluster, uuid), listener);

            nodeKeeper.startListeners();

            log.info("... running");

            zookeeperInitEvent.fire(new ZookeeperInitEvent());
        } catch (KeeperException ex) {
            log.error("could not initialise Zookeeper: {}", ex.getMessage());
        } catch (NodeKeeperException e) {
            log.error("could not initialise NodeKeeper: {}", e.getMessage());
        }
    } else {
        log.warn("no Zookeeper servers configured, Zookeeper Integration not available");
    }

}

From source file:org.cloudata.util.upgrade.CloudataUpgrade.java

License:Apache License

private static void modifyMetaMapFile() throws IOException {
    LOG.info("====== Start modifyMetaMapFile");

    try {/*from   www  . ja va 2s  .  c o  m*/
        //      TabletInfo rootTablet14 = Tablet.getRootTabletInfo(conf, zk);
        //      TabletInfo13 rootTablet = new TabletInfo13();
        //      rootTablet.tableName = rootTablet14.getTableName();
        //      rootTablet.tabletName = rootTablet14.getTabletName();
        //      rootTablet.endRowKey = rootTablet14.getEndRowKey();
        //      rootTablet.assignedHostName = rootTablet14.getAssignedHostName();

        TabletInfo13 rootTablet = getRootTabletInfo(conf, zk);
        if (rootTablet == null) {
            throw new IOException("Root Tablet is : " + rootTablet);
        }

        //////////////////////////////////////////////////////////////////////
        //ROOT Tablet
        List<MapFileColumnValue> mapFileColumnValues = getTabletInfos(rootTablet);
        if (mapFileColumnValues.size() == 0) {
            LOG.warn("No META TableInfo in ROOT Tablet:" + rootTablet);
            return;
        }

        SortedSet<TabletInfo13> metaTablets = new TreeSet<TabletInfo13>();
        UpgradeFileWriter writer = new UpgradeFileWriter(rootTablet.tabletName);
        try {
            Row.Key startRowKey = Row.Key.MIN_KEY;
            String previousTableName = null;
            for (MapFileColumnValue eachColumnValue : mapFileColumnValues) {
                if (eachColumnValue.isDeleted()) {
                    writer.write(eachColumnValue);
                } else {
                    TabletInfo13 tabletInfo13 = new TabletInfo13();
                    tabletInfo13.readFields(eachColumnValue.getValue());
                    TabletInfo14 tabletInfo = tabletInfo13.getTabletInfo();

                    if (previousTableName != null && !previousTableName.equals(tabletInfo13.tableName)) {
                        startRowKey = Row.Key.MIN_KEY;
                    }
                    tabletInfo.startRowKey = startRowKey;

                    Row.Key rowKey = Tablet.generateMetaRowKey(tabletInfo.tableName, tabletInfo.endRowKey);
                    Cell cell = new Cell(new Cell.Key(tabletInfo.tabletName), tabletInfo.getWriteBytes());
                    ColumnValue columnValue = new ColumnValue();
                    columnValue.setRowKey(rowKey);
                    columnValue.setCellKey(cell.getKey());
                    cell.getValue().copyToColumnValue(columnValue);
                    columnValue.setDeleted(eachColumnValue.isDeleted());
                    columnValue.setTimestamp(eachColumnValue.getTimestamp());

                    MapFileColumnValue mapFileColumnValue = new MapFileColumnValue();
                    ValueCollection.copyMapFileColumnValue(columnValue, mapFileColumnValue);
                    writer.write(mapFileColumnValue);
                    metaTablets.add(tabletInfo13);

                    startRowKey = tabletInfo13.endRowKey;
                    previousTableName = tabletInfo13.tableName;
                }
            }
        } finally {
            writer.close();
        }

        //////////////////////////////////////////////////////////////////////
        //META Tablet
        for (TabletInfo13 eachMetaTablet : metaTablets) {
            mapFileColumnValues = getTabletInfos(eachMetaTablet);
            if (mapFileColumnValues.size() == 0) {
                LOG.warn("No USER TableInfo in META Tablet:" + eachMetaTablet);
                continue;
            }
            writer = new UpgradeFileWriter(eachMetaTablet.tabletName);
            try {
                Row.Key startRowKey = Row.Key.MIN_KEY;

                TabletInfo14 previousTablet = null;
                //          Row.Key prevoiusEndRowKey = null;
                //          String previousTableName = null;
                //          String previousTabletName = null;

                for (MapFileColumnValue eachColumnValue : mapFileColumnValues) {
                    if (eachColumnValue.isDeleted()) {
                        writer.write(eachColumnValue);
                    } else {
                        TabletInfo13 tabletInfo13 = new TabletInfo13();
                        tabletInfo13.readFields(eachColumnValue.getValue());
                        TabletInfo14 tabletInfo14 = tabletInfo13.getTabletInfo();

                        if (previousTablet != null) {
                            if (!previousTablet.tableName.equals(tabletInfo13.tableName)) {
                                startRowKey = Row.Key.MIN_KEY;
                            } else {
                                if (!previousTablet.tabletName.equals(tabletInfo13.tabletName)
                                        && !previousTablet.endRowKey.equals(tabletInfo13.endRowKey)) {
                                    startRowKey = previousTablet.endRowKey;
                                }
                            }
                        }

                        tabletInfo14.startRowKey = startRowKey;
                        System.out.println(">>>>" + tabletInfo14.tabletName + ">"
                                + (startRowKey.equals(Row.Key.MIN_KEY) ? "MIN" : startRowKey) + "~"
                                + (tabletInfo14.endRowKey.equals(Row.Key.MAX_KEY) ? "MAX"
                                        : tabletInfo14.endRowKey)
                                + ">" + eachColumnValue.getTimestamp() + ">" + eachColumnValue.isDeleted()
                                + ">");

                        Row.Key rowKey = Tablet.generateMetaRowKey(tabletInfo14.tableName,
                                tabletInfo14.endRowKey);
                        Cell cell = new Cell(new Cell.Key(tabletInfo14.tabletName),
                                tabletInfo14.getWriteBytes());
                        ColumnValue columnValue = new ColumnValue();
                        columnValue.setRowKey(rowKey);
                        columnValue.setCellKey(cell.getKey());
                        cell.getValue().copyToColumnValue(columnValue);
                        columnValue.setDeleted(eachColumnValue.isDeleted());
                        columnValue.setTimestamp(eachColumnValue.getTimestamp());

                        MapFileColumnValue mapFileColumnValue = new MapFileColumnValue();
                        ValueCollection.copyMapFileColumnValue(columnValue, mapFileColumnValue);
                        writer.write(mapFileColumnValue);

                        //              prevoiusEndRowKey = tabletInfo13.endRowKey;
                        //              previousTabletName = tabletInfo13.tabletName;
                        //              previousTableName = tabletInfo13.tableName;

                        previousTablet = tabletInfo14;
                    }
                }
            } finally {
                writer.close();
            }
        }

        LOG.info("====== Modify ROOT TabletInfo in ZooKeeper: "
                + LockUtil.getZKPath(conf, Constants.ROOT_TABLET));
        TabletInfo14 newRootTablet = rootTablet.getTabletInfo();
        newRootTablet.startRowKey = Row.Key.MIN_KEY;

        try {
            zk.setData(LockUtil.getZKPath(conf, Constants.ROOT_TABLET), newRootTablet.getWriteBytes(), -1);
        } catch (KeeperException e) {
            LOG.error(e);
        } catch (InterruptedException e) {
            LOG.error(e);
        }
    } catch (Exception e) {
        LOG.error("Error:" + e.getMessage(), e);
    } finally {
        LOG.info("====== End modifyMetaMapFile");
    }
}

From source file:org.eclipse.ecf.provider.zookeeper.node.internal.NodeWriter.java

License:Open Source License

public synchronized void publish() {
    try {// w  w w  .  j a  va2 s  .c o  m
        String parentPath = this.getNode().getAbsolutePath();
        Stat stat = this.writeRoot.getWriteKeeper().exists(parentPath, false);
        if (stat == null) {
            this.writeRoot.getWriteKeeper().create(parentPath,
                    ((AdvertisedService) this.getNode().getWrappedService()).getPropertiesAsBytes(),
                    Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        }
        Logger.log(LogService.LOG_INFO,
                PrettyPrinter.prompt(PrettyPrinter.PUBLISHED, this.getNode().getWrappedService()), null);
    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.CONNECTIONLOSS) {
            Logger.log(LogService.LOG_ERROR, "Can't connect to server! " + e.getMessage(), e);
        }
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:org.midonet.midolman.state.ZkManager.java

License:Apache License

private String getMultiErrorMessage(List<Op> ops, KeeperException ex) {
    List<OpResult> results = ex.getResults();
    if (results == null || results.isEmpty()) {
        return "executing multi ops: " + ex.getMessage();
    }//from   ww w . jav  a2 s. co  m

    StringBuilder msg = new StringBuilder("executing multi ops: ");

    // Use counter to iterate through op and result lists in parallel.
    for (int i = 0; i < results.size(); i++) {
        OpResult result = results.get(i);
        if (result instanceof OpResult.ErrorResult) {
            int errorCode = ((OpResult.ErrorResult) result).getErr();
            if (errorCode != 0) {
                Op operation = ops.get(i);
                msg.append("\r\n\t\t");
                msg.append(operation.getPath());
                msg.append(" failed with error code: ");
                msg.append(errorCode);
            }
        }
    }

    return msg.toString();
}

From source file:org.neo4j.backup.Backup.java

License:Open Source License

public static void main(String[] args) {
    Args arguments = new Args(args);
    boolean full = arguments.has(FULL);
    boolean incremental = arguments.has(INCREMENTAL);
    if (full & incremental || !(full | incremental)) {
        System.out.println("Specify either " + dash(FULL) + " or " + dash(INCREMENTAL));
        exitAbnormally();//  ww w .j  a  va  2  s  . co  m
    }

    String from = arguments.get(FROM, null);
    String fromHa = arguments.get(FROM_HA, null);
    if ((from != null && fromHa != null) || (from == null && fromHa == null)) {
        System.out.println("Specify either " + dash(FROM) + " or " + dash(FROM_HA));
        exitAbnormally();
    }

    String to = arguments.get(TO, null);
    if (to == null) {
        System.out.println("Specify target location with " + dash(TO) + " <target-directory>");
        exitAbnormally();
    }

    if (fromHa != null) {
        // This means we're trying to reach an HA cluster, a ZooKeeper service
        // managing that cluster, that is.
        try {
            System.out.println("Asking ZooKeeper service at '" + fromHa + "' for master");
            from = getMasterServerInCluster(fromHa);
            System.out.println("Found master '" + from + "' in cluster");
        } catch (ComException e) {
            System.out.println(e.getMessage());
            exitAbnormally();
        } catch (RuntimeException e) {
            if (e.getCause() instanceof KeeperException) {
                KeeperException zkException = (KeeperException) e.getCause();
                System.out.println("Couldn't connect to '" + fromHa + "', " + zkException.getMessage());
                exitAbnormally();
            }
            throw e;
        }
    }

    doBackup(full, from, to);
}

From source file:org.neo4j.kernel.ha.backup.HaBackupProvider.java

License:Open Source License

@Override
public URI resolve(URI address, Args args) {
    String master = null;//from ww w  . j  ava2 s  .c o  m
    try {
        System.out.println("Asking coordinator service at '" + address + "' for master");

        // At first HaConfig.CONFIG_KEY_CLUSTER_NAME was used
        String clusterName = args.get(HaSettings.cluster_name.name(), null);
        // but then later on -cluster was also added because it looks much nicer.
        if (clusterName == null) {
            clusterName = args.get("cluster",
                    ConfigurationDefaults.getDefault(HaSettings.cluster_name, HaSettings.class));
        }
        master = getMasterServerInCluster(address.getSchemeSpecificPart().substring(2), clusterName); // skip the "//" part
        System.out.println("Found master '" + master + "' in cluster");
    } catch (ComException e) {
        throw e;
    } catch (RuntimeException e) {
        if (e.getCause() instanceof KeeperException) {
            KeeperException zkException = (KeeperException) e.getCause();
            System.out.println("Couldn't connect to '" + address + "', " + zkException.getMessage());
        }
        throw e;
    }
    URI toReturn = null;
    try {
        toReturn = new URI(master);
    } catch (URISyntaxException e) {
        // no way
    }
    return toReturn;
}

From source file:pt.uminho.di.tests.zookeeper.ManagedZooKeeperClient.java

License:Apache License

public void initializeLogDirectories() {
    // create directory if it doesn't exist
    String[] pathParts = { "log", "entries" };

    StringBuilder pathSB = new StringBuilder();
    for (String pathElement : pathParts) {
        pathSB.append('/').append(pathElement);
        String pathString = pathSB.toString();
        //send requests to create all parts of the path without waiting for the
        //results of previous calls to return
        try {//  w  w  w.j  ava 2s .  c om
            Stat response = zooKeeper.exists(pathString, false);
            logger.info(pathString + " exists? Response: " + response);
            if (response == null) {
                String reply = zooKeeper.create(pathString, null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
                logger.info("Create " + pathString + " : " + reply);
            }
        } catch (KeeperException ex) {
            logger.error(ex.getMessage(), ex);
        } catch (InterruptedException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}