org.apache.zookeeper.KeeperException#code ( )源码实例Demo

下面列出了org.apache.zookeeper.KeeperException#code ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hbase   文件: RecoverableZooKeeper.java

/**
 * 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();
    }
  }
}
 
源代码2 项目: azeroth   文件: ResourceClaim.java

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;
}
 
源代码3 项目: hbase   文件: RecoverableZooKeeper.java

/**
 * 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();
    }
  }
}
 
源代码4 项目: hadoop   文件: ActiveStandbyElector.java

/**
 * 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;
    }
  }
}
 
源代码5 项目: nifi   文件: ZooKeeperStateProvider.java

@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);
    }
}
 
源代码6 项目: lucene-solr   文件: SolrSnapshotManager.java

/**
 * 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;
}
 
源代码7 项目: hbase   文件: RecoverableZooKeeper.java

/**
 * 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();
    }
  }
}
 
源代码8 项目: java-uniqueid   文件: ResourceClaim.java

/**
 * 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;
}
 
源代码9 项目: hbase   文件: RecoverableZooKeeper.java

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();
    }
  }
}
 
源代码10 项目: TakinRPC   文件: ZkException.java

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);
    }
}
 

/**
 * 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);
}
 

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;
        }
    }
}
 
源代码13 项目: java-uniqueid   文件: ZooKeeperHelper.java

/**
 * 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;
        }
    }
}
 
源代码14 项目: Scribengin   文件: RegistryImpl.java

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) ;
}
 
源代码15 项目: spliceengine   文件: ZkUtils.java

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;
    }
}
 
源代码16 项目: lucene-solr   文件: Overseer.java

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);
}
 
源代码17 项目: java-uniqueid   文件: ResourceClaim.java

/**
 * 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;
        }
    }
}
 
源代码18 项目: hbase   文件: RecoverableZooKeeper.java

/**
 * 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;
    }
  }
}
 
源代码19 项目: hbase   文件: RecoverableZooKeeper.java

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;
  }
}
 
源代码20 项目: distributedlog   文件: ZKException.java

public ZKException(String msg, KeeperException exception) {
    super(StatusCode.ZOOKEEPER_ERROR, msg, exception);
    this.code = exception.code();
}