Java Code Examples for org.apache.zookeeper.KeeperException#code()

The following examples show how to use org.apache.zookeeper.KeeperException#code() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * setAcl is an idempotent operation. Retry before throwing exception
 * @return list of ACLs
 */
public Stat setAcl(String path, List<ACL> acls, int version)
  throws KeeperException, InterruptedException {
  try (TraceScope scope = TraceUtil.createTrace("RecoverableZookeeper.setAcl")) {
    RetryCounter retryCounter = retryCounterFactory.create();
    while (true) {
      try {
        return checkZk().setACL(path, acls, version);
      } catch (KeeperException e) {
        switch (e.code()) {
          case CONNECTIONLOSS:
            retryOrThrow(retryCounter, e, "setAcl");
            break;
          case OPERATIONTIMEOUT:
            retryOrThrow(retryCounter, e, "setAcl");
            break;

          default:
            throw e;
        }
      }
      retryCounter.sleepUntilNextRetry();
    }
  }
}
 
Example 2
Source File: ResourceClaim.java    From java-uniqueid with Apache License 2.0 6 votes vote down vote up
/**
 * Grab a ticket in the queue.
 *
 * @param zookeeper ZooKeeper connection to use.
 * @param lockNode Path to the znode representing the locking queue.
 * @param ticket Name of the ticket to attempt to grab.
 * @return True on success, false if the ticket was already grabbed by another process.
 */
static boolean grabTicket(ZooKeeper zookeeper, String lockNode, String ticket)
        throws InterruptedException, KeeperException {
    try {
        zookeeper.create(lockNode + "/" + ticket, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NODEEXISTS) {
            // It is possible that two processes try to grab the exact same ticket at the same time.
            // This is common for the locking ticket.
            logger.debug("Failed to claim ticket {}.", ticket);
            return false;
        } else {
            throw e;
        }
    }
    logger.debug("Claimed ticket {}.", ticket);
    return true;
}
 
Example 3
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Run multiple operations in a transactional manner. Retry before throwing exception
 */
public List<OpResult> multi(Iterable<Op> ops)
  throws KeeperException, InterruptedException {
  try (TraceScope scope = TraceUtil.createTrace("RecoverableZookeeper.multi")) {
    RetryCounter retryCounter = retryCounterFactory.create();
    Iterable<Op> multiOps = prepareZKMulti(ops);
    while (true) {
      try {
        return checkZk().multi(multiOps);
      } catch (KeeperException e) {
        switch (e.code()) {
          case CONNECTIONLOSS:
            retryOrThrow(retryCounter, e, "multi");
            break;
          case OPERATIONTIMEOUT:
            retryOrThrow(retryCounter, e, "multi");
            break;

          default:
            throw e;
        }
      }
      retryCounter.sleepUntilNextRetry();
    }
  }
}
 
Example 4
Source File: SolrSnapshotManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns the {@linkplain CollectionSnapshotMetaData} for each named snapshot for the specified collection in Zookeeper.
 *
 * @param zkClient Zookeeper client
 * @param collectionName The name of the collection
 * @return the {@linkplain CollectionSnapshotMetaData} for each named snapshot
 * @throws InterruptedException In case of thread interruption.
 * @throws KeeperException In case of Zookeeper error
 */
public static Collection<CollectionSnapshotMetaData> listSnapshots(SolrZkClient zkClient, String collectionName)
    throws InterruptedException, KeeperException {
  Collection<CollectionSnapshotMetaData> result = new ArrayList<>();
  String zkPath = getSnapshotMetaDataZkPath(collectionName, Optional.empty());

  try {
    Collection<String> snapshots = zkClient.getChildren(zkPath, null, true);
    for (String snapshot : snapshots) {
      Optional<CollectionSnapshotMetaData> s = getCollectionLevelSnapshot(zkClient, collectionName, snapshot);
      if (s.isPresent()) {
        result.add(s.get());
      }
    }
  } catch (KeeperException ex) {
    // Gracefully handle the case when the zk node doesn't exist (e.g. due to a concurrent delete collection operation).
    if ( ex.code() != KeeperException.Code.NONODE ) {
      throw ex;
    }
  }
  return result;
}
 
Example 5
Source File: ZooKeeperStateProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void onComponentRemoved(final String componentId) throws IOException {
    try {
        ZKUtil.deleteRecursive(getZooKeeper(), getComponentPath(componentId));
    } catch (final KeeperException ke) {
        // Node doesn't exist so just ignore
        final Code exceptionCode = ke.code();
        if (Code.NONODE == exceptionCode) {
            return;
        }
        if (Code.SESSIONEXPIRED == exceptionCode) {
            invalidateClient();
            onComponentRemoved(componentId);
            return;
        }

        throw new IOException("Unable to remove state for component with ID '" + componentId + " with exception code " + exceptionCode, ke);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Failed to remove state for component with ID '" + componentId + "' from ZooKeeper due to being interrupted", e);
    }
}
 
Example 6
Source File: ActiveStandbyElector.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * get data set by the active leader
 * 
 * @return data set by the active instance
 * @throws ActiveNotFoundException
 *           when there is no active leader
 * @throws KeeperException
 *           other zookeeper operation errors
 * @throws InterruptedException
 * @throws IOException
 *           when ZooKeeper connection could not be established
 */
public synchronized byte[] getActiveData() throws ActiveNotFoundException,
    KeeperException, InterruptedException, IOException {
  try {
    if (zkClient == null) {
      createConnection();
    }
    Stat stat = new Stat();
    return getDataWithRetries(zkLockFilePath, false, stat);
  } catch(KeeperException e) {
    Code code = e.code();
    if (isNodeDoesNotExist(code)) {
      // handle the commonly expected cases that make sense for us
      throw new ActiveNotFoundException();
    } else {
      throw e;
    }
  }
}
 
Example 7
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * getAcl is an idempotent operation. Retry before throwing exception
 * @return list of ACLs
 */
public List<ACL> getAcl(String path, Stat stat)
  throws KeeperException, InterruptedException {
  try (TraceScope scope = TraceUtil.createTrace("RecoverableZookeeper.getAcl")) {
    RetryCounter retryCounter = retryCounterFactory.create();
    while (true) {
      try {
        return checkZk().getACL(path, stat);
      } catch (KeeperException e) {
        switch (e.code()) {
          case CONNECTIONLOSS:
            retryOrThrow(retryCounter, e, "getAcl");
            break;
          case OPERATIONTIMEOUT:
            retryOrThrow(retryCounter, e, "getAcl");
            break;

          default:
            throw e;
        }
      }
      retryCounter.sleepUntilNextRetry();
    }
  }
}
 
Example 8
Source File: ResourceClaim.java    From azeroth with Apache License 2.0 6 votes vote down vote up
static boolean grabTicket(ZooKeeper zookeeper, String lockNode,
                          String ticket) throws InterruptedException, KeeperException {
    try {
        zookeeper.create(lockNode + "/" + ticket, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.EPHEMERAL);
    } catch (KeeperException e) {
        if (e.code() == KeeperException.Code.NODEEXISTS) {
            logger.debug("Failed to claim ticket {}.", ticket);
            return false;
        } else {
            throw e;
        }
    }
    logger.debug("Claimed ticket {}.", ticket);
    return true;
}
 
Example 9
Source File: ZooKeeperHelper.java    From java-uniqueid with Apache License 2.0 5 votes vote down vote up
/**
 * Create an empty normal (persistent) Znode. If the znode already exists, do nothing.
 *
 * @param zookeeper ZooKeeper instance to work with.
 * @param znode     Znode to create.
 * @throws KeeperException
 * @throws InterruptedException
 */
static void createIfNotThere(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException {
    try {
        create(zookeeper, znode);
    } catch (KeeperException e) {
        if (e.code() != KeeperException.Code.NODEEXISTS) {
            // Rethrow all exceptions, except "node exists",
            // because if the node exists, this method reached its goal.
            throw e;
        }
    }
}
 
Example 10
Source File: ResourceTestPoolHelper.java    From java-uniqueid with Apache License 2.0 5 votes vote down vote up
public static void deleteLockingTicket(ZooKeeper zookeeper, String znode)
        throws KeeperException, InterruptedException {
    try {
        zookeeper.delete(znode + "/queue/" + LOCKING_TICKET, -1);
    } catch (KeeperException e) {
        if (e.code() != KeeperException.Code.NONODE) {
            throw e;
        }
    }
}
 
Example 11
Source File: ResourceTestPoolHelper.java    From java-uniqueid with Apache License 2.0 5 votes vote down vote up
/**
 * Create the two znodes used for the queue and the resource pool.
 *
 * @param zookeeper ZooKeeper connection to use.
 */
public static void prepareEmptyQueueAndPool(ZooKeeper zookeeper, String znode)
        throws KeeperException, InterruptedException {
    try {
        zookeeper.create(znode, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    } catch (KeeperException e) {
        if (e.code() != KeeperException.Code.NODEEXISTS) {
            throw e;
        }
    }
    zookeeper.create(znode + "/queue", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    zookeeper.create(znode + "/pool", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
 
Example 12
Source File: RegistryImpl.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
private RegistryException toRegistryException(String message, Throwable t) {
  if(t instanceof InterruptedException) {
    return new RegistryException(ErrorCode.Timeout, message, t) ;
  } else if(t instanceof KeeperException) {
    KeeperException kEx = (KeeperException) t;
    if(kEx.code() ==  KeeperException.Code.NONODE) {
      return new RegistryException(ErrorCode.NoNode, message, t) ;
    }
  }
  return new RegistryException(ErrorCode.Unknown, message, t) ;
}
 
Example 13
Source File: ZkUtils.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean safeDelete(String path,int version) throws KeeperException, InterruptedException{
    try{
        getRecoverableZooKeeper().delete(path,version);
        return true;
    }catch(KeeperException e){
        if(e.code()!=KeeperException.Code.NONODE)
            throw e;
        else
            return false;
    }
}
 
Example 14
Source File: Overseer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private boolean isBadMessage(Exception e) {
  if (e instanceof KeeperException) {
    KeeperException ke = (KeeperException) e;
    return ke.code() == KeeperException.Code.NONODE || ke.code() == KeeperException.Code.NODEEXISTS;
  }
  return !(e instanceof InterruptedException);
}
 
Example 15
Source File: ResourceClaim.java    From java-uniqueid with Apache License 2.0 5 votes vote down vote up
/**
 * Release an acquired lock.
 *
 * @param zookeeper ZooKeeper connection to use.
 * @param lockNode Path to the znode representing the locking queue.
 * @param ticket Name of the first node in the queue.
 */
static void releaseTicket(ZooKeeper zookeeper, String lockNode, String ticket)
        throws KeeperException, InterruptedException {

    logger.debug("Releasing ticket {}.", ticket);
    try {
        zookeeper.delete(lockNode + "/" + ticket, -1);
    } catch (KeeperException e) {
        if (e.code() != KeeperException.Code.NONODE) {
            // If it the node is already gone, than that is fine, otherwise:
            throw e;
        }
    }
}
 
Example 16
Source File: ZkException.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
public static ZkException create(KeeperException e) {
    switch (e.code()) {
        // case DATAINCONSISTENCY:
        // return new DataInconsistencyException();
        // case CONNECTIONLOSS:
        // return new ConnectionLossException();
        case NONODE:
            return new ZkNoNodeException(e);
        // case NOAUTH:
        // return new ZkNoAuthException();
        case BADVERSION:
            return new ZkBadVersionException(e);
        // case NOCHILDRENFOREPHEMERALS:
        // return new NoChildrenForEphemeralsException();
        case NODEEXISTS:
            return new ZkNodeExistsException(e);
        // case INVALIDACL:
        // return new ZkInvalidACLException();
        // case AUTHFAILED:
        // return new AuthFailedException();
        // case NOTEMPTY:
        // return new NotEmptyException();
        // case SESSIONEXPIRED:
        // return new SessionExpiredException();
        // case INVALIDCALLBACK:
        // return new InvalidCallbackException();

        default:
            return new ZkException(e);
    }
}
 
Example 17
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 5 votes vote down vote up
private byte[] getData(String path, Watcher watcher, Boolean watch, Stat stat)
        throws InterruptedException, KeeperException {
  try (TraceScope scope = TraceUtil.createTrace("RecoverableZookeeper.getData")) {
    RetryCounter retryCounter = retryCounterFactory.create();
    while (true) {
      try {
        byte[] revData;
        if (watch == null) {
          revData = checkZk().getData(path, watcher, stat);
        } else {
          revData = checkZk().getData(path, watch, stat);
        }
        return ZKMetadata.removeMetaData(revData);
      } catch (KeeperException e) {
        switch (e.code()) {
          case CONNECTIONLOSS:
            retryOrThrow(retryCounter, e, "getData");
            break;
          case OPERATIONTIMEOUT:
            retryOrThrow(retryCounter, e, "getData");
            break;

          default:
            throw e;
        }
      }
      retryCounter.sleepUntilNextRetry();
    }
  }
}
 
Example 18
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 4 votes vote down vote up
private String createNonSequential(String path, byte[] data, List<ACL> acl,
    CreateMode createMode) throws KeeperException, InterruptedException {
  RetryCounter retryCounter = retryCounterFactory.create();
  boolean isRetry = false; // False for first attempt, true for all retries.
  while (true) {
    try {
      return checkZk().create(path, data, acl, createMode);
    } catch (KeeperException e) {
      switch (e.code()) {
        case NODEEXISTS:
          if (isRetry) {
            // If the connection was lost, there is still a possibility that
            // we have successfully created the node at our previous attempt,
            // so we read the node and compare.
            byte[] currentData = checkZk().getData(path, false, null);
            if (currentData != null &&
                Bytes.compareTo(currentData, data) == 0) {
              // We successfully created a non-sequential node
              return path;
            }
            LOG.error("Node " + path + " already exists with " +
                Bytes.toStringBinary(currentData) + ", could not write " +
                Bytes.toStringBinary(data));
            throw e;
          }
          LOG.trace("Node {} already exists", path);
          throw e;

        case CONNECTIONLOSS:
          retryOrThrow(retryCounter, e, "create");
          break;
        case OPERATIONTIMEOUT:
          retryOrThrow(retryCounter, e, "create");
          break;

        default:
          throw e;
      }
    }
    retryCounter.sleepUntilNextRetry();
    isRetry = true;
  }
}
 
Example 19
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 4 votes vote down vote up
/**
 * setData is NOT an idempotent operation. Retry may cause BadVersion Exception
 * Adding an identifier field into the data to check whether
 * badversion is caused by the result of previous correctly setData
 * @return Stat instance
 */
public Stat setData(String path, byte[] data, int version)
  throws KeeperException, InterruptedException {
  try (TraceScope scope = TraceUtil.createTrace("RecoverableZookeeper.setData")) {
    RetryCounter retryCounter = retryCounterFactory.create();
    byte[] newData = ZKMetadata.appendMetaData(id, data);
    boolean isRetry = false;
    while (true) {
      try {
        return checkZk().setData(path, newData, version);
      } catch (KeeperException e) {
        switch (e.code()) {
          case CONNECTIONLOSS:
            retryOrThrow(retryCounter, e, "setData");
            break;
          case OPERATIONTIMEOUT:
            retryOrThrow(retryCounter, e, "setData");
            break;
          case BADVERSION:
            if (isRetry) {
              // try to verify whether the previous setData success or not
              try{
                Stat stat = new Stat();
                byte[] revData = checkZk().getData(path, false, stat);
                if(Bytes.compareTo(revData, newData) == 0) {
                  // the bad version is caused by previous successful setData
                  return stat;
                }
              } catch(KeeperException keeperException){
                // the ZK is not reliable at this moment. just throwing exception
                throw keeperException;
              }
            }
          // throw other exceptions and verified bad version exceptions
          default:
            throw e;
        }
      }
      retryCounter.sleepUntilNextRetry();
      isRetry = true;
    }
  }
}
 
Example 20
Source File: ZKException.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
public ZKException(String msg, KeeperException exception) {
    super(StatusCode.ZOOKEEPER_ERROR, msg, exception);
    this.code = exception.code();
}