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

The following examples show how to use org.apache.zookeeper.KeeperException.Code#get() . 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: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 6 votes vote down vote up
public void processResult(int rc, 
        String path, 
        Object ctx, 
        List<String> children){    
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getStatuses();
        
        break;
    case OK:
        LOG.info("Processing assignments for recovery");
        status = children;
        processAssignments();
        
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
        cb.recoveryComplete(RecoveryCallback.FAILED, null);
    }
}
 
Example 2
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 6 votes vote down vote up
public void processResult(int rc, String path, Object ctx, String name) {
    switch(Code.get(rc)) {
    case CONNECTIONLOSS:
        recreateTask((RecreateTaskCtx) ctx);
       
        break;
    case OK:
        deleteAssignment(((RecreateTaskCtx) ctx).path);
        
        break;
    case NODEEXISTS:
        LOG.warn("Node shouldn't exist: " + path);
        
        break;
    default:
        LOG.error("Something wwnt wrong when recreating task", 
                KeeperException.create(Code.get(rc)));
    }
}
 
Example 3
Source File: ZkAsyncCallbacks.java    From helix with Apache License 2.0 6 votes vote down vote up
/**
 * @param rc the return code
 * @return true if the error is transient and the operation may succeed when being retried.
 */
private boolean needRetry(int rc) {
  try {
    switch (Code.get(rc)) {
    /** Connection to the server has been lost */
    case CONNECTIONLOSS:
      /** The session has been expired by the server */
    case SESSIONEXPIRED:
      /** Session moved to another server, so operation is ignored */
    case SESSIONMOVED:
      return true;
    default:
      return false;
    }
  } catch (ClassCastException | NullPointerException ex) {
    LOG.error("Failed to handle unknown return code {}. Skip retrying.", rc, ex);
    return false;
  }
}
 
Example 4
Source File: TestApi.java    From jframe with Apache License 2.0 6 votes vote down vote up
public void testCreate() {
    class CreateCallback implements StringCallback {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            LOG.info("code->{} path->{}", rc, path);
            switch (Code.get(rc)) {
            case CONNECTIONLOSS:
                // TODO re-create
                break;
            case OK:
                break;
            case NODEEXISTS:
                break;
            default:
                LOG.error("error code->{} path->{}", rc, path);
            }
        }

    }

    if (zk != null)
        zk.create("/test", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new CreateCallback(), null);
}
 
Example 5
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 6 votes vote down vote up
public void processResult(int rc, String path, Object ctx, List<String> children){    
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getAssignedWorkers();
        
        break;
    case OK:  
        assignedWorkers = children;
        getWorkers(children);

        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
        cb.recoveryComplete(RecoveryCallback.FAILED, null);
    }
}
 
Example 6
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 6 votes vote down vote up
public void processResult(int rc, String path, Object ctx, List<String> children){
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getTasks();
        
        break;
    case OK:
        LOG.info("Getting tasks for recovery");
        tasks = children;
        getAssignedWorkers();
        
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
        cb.recoveryComplete(RecoveryCallback.FAILED, null);
    }
}
 
Example 7
Source File: OrphanStatuses.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void processResult(int rc, String path, Object ctx){
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        zk.delete(path, -1, deleteStatusCallback, null);
        break;
    case OK:
        LOG.info("Succesfully deleted orphan status znode: " + path);
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path)); 
    }
}
 
Example 8
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void processResult(int rc, String path, Object rtx){
    switch(Code.get(rc)) {
    case CONNECTIONLOSS:
        deleteAssignment(path);
        break;
    case OK:
        LOG.info("Task correctly deleted: " + path);
        break;
    default:
        LOG.error("Failed to delete task data" + 
                KeeperException.create(Code.get(rc), path));
    } 
}
 
Example 9
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat)  {
    switch(Code.get(rc)) {
    case CONNECTIONLOSS:
        getDataReassign(path, (String) ctx); 
        
        break;
    case OK:
        recreateTask(new RecreateTaskCtx(path, (String) ctx, data));
        
        break;
    default:
        LOG.error("Something went wrong when getting data ",
                KeeperException.create(Code.get(rc)));
    }
}
 
Example 10
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void processResult(int rc, String path, Object ctx, List<String> children){    
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getWorkers(ctx);
        break;
    case OK:
        LOG.info("Getting worker assignments for recovery: " + children.size());
        
        /*
         * No worker available yet, so the master is probably let's just return an empty list.
         */
        if(children.size() == 0) {
            LOG.warn( "Empty list of workers, possibly just starting" );
            cb.recoveryComplete(RecoveryCallback.OK, new ArrayList<String>());
            
            break;
        }
        
        /*
         * Need to know which of the assigned workers are active.
         */
                
        activeWorkers = children;
        
        for(String s : assignedWorkers){
            getWorkerAssignments("/assign/" + s);
        }
        
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
        cb.recoveryComplete(RecoveryCallback.FAILED, null);
    }
}
 
Example 11
Source File: OrphanStatuses.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void processResult(int rc, String path, Object ctx, List<String> children){
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getTasks();
        break;
    case OK:
        statuses = children;
        processTasks();
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
    } 
}
 
Example 12
Source File: OrphanStatuses.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void processResult(int rc, String path, Object ctx, List<String> children){
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getTasks();
        break;
    case OK:
        tasks = children;
        getStatuses();
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
    } 
}
 
Example 13
Source File: ZkBaseDataAccessor.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * async create
 * TODO: rename to create
 */
@Override
public boolean[] createChildren(List<String> paths, List<T> records, int options) {
  boolean[] success = new boolean[paths.size()];

  CreateMode mode = AccessOption.getMode(options);
  if (mode == null) {
    LOG.error("Invalid async create mode. options: " + options);
    return success;
  }

  boolean[] needCreate = new boolean[paths.size()];
  Arrays.fill(needCreate, true);
  List<List<String>> pathsCreated =
      new ArrayList<>(Collections.<List<String>>nCopies(paths.size(), null));

  long startT = System.nanoTime();
  try {

    ZkAsyncCallbacks.CreateCallbackHandler[] cbList =
        create(paths, records, needCreate, pathsCreated, options);

    for (int i = 0; i < cbList.length; i++) {
      ZkAsyncCallbacks.CreateCallbackHandler cb = cbList[i];
      success[i] = (Code.get(cb.getRc()) == Code.OK);
    }

    return success;
  } finally {
    long endT = System.nanoTime();
    if (LOG.isTraceEnabled()) {
      LOG.trace(
          "create_async, size: " + paths.size() + ", paths: " + paths.get(0) + ",... time: " + (
              endT - startT) + " ns");
    }
  }
}
 
Example 14
Source File: ZkCacheBaseDataAccessor.java    From helix with Apache License 2.0 5 votes vote down vote up
@Override
public boolean[] createChildren(List<String> paths, List<T> records, int options) {
  final int size = paths.size();
  List<String> serverPaths = prependChroot(paths);

  Cache<T> cache = getCache(serverPaths);
  if (cache != null) {
    try {
      cache.lockWrite();
      boolean[] needCreate = new boolean[size];
      Arrays.fill(needCreate, true);
      List<List<String>> pathsCreatedList =
          new ArrayList<List<String>>(Collections.<List<String>>nCopies(size, null));
      ZkAsyncCallbacks.CreateCallbackHandler[] createCbList =
          _baseAccessor.create(serverPaths, records, needCreate, pathsCreatedList, options);

      boolean[] success = new boolean[size];
      for (int i = 0; i < size; i++) {
        ZkAsyncCallbacks.CreateCallbackHandler cb = createCbList[i];
        success[i] = (Code.get(cb.getRc()) == Code.OK);

        updateCache(cache, pathsCreatedList.get(i), success[i], serverPaths.get(i),
            records.get(i), ZNode.ZERO_STAT);
      }

      return success;
    } finally {
      cache.unlockWrite();
    }
  }

  // no cache
  return _baseAccessor.createChildren(serverPaths, records, options);
}
 
Example 15
Source File: ActiveStandbyElector.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * interface implementation of Zookeeper callback for create
 */
@Override
public synchronized void processResult(int rc, String path, Object ctx,
    String name) {
  if (isStaleClient(ctx)) return;
  LOG.debug("CreateNode result: " + rc + " for path: " + path
      + " connectionState: " + zkConnectionState +
      "  for " + this);

  Code code = Code.get(rc);
  if (isSuccess(code)) {
    // we successfully created the znode. we are the leader. start monitoring
    if (becomeActive()) {
      monitorActiveStatus();
    } else {
      reJoinElectionAfterFailureToBecomeActive();
    }
    return;
  }

  if (isNodeExists(code)) {
    if (createRetryCount == 0) {
      // znode exists and we did not retry the operation. so a different
      // instance has created it. become standby and monitor lock.
      becomeStandby();
    }
    // if we had retried then the znode could have been created by our first
    // attempt to the server (that we lost) and this node exists response is
    // for the second attempt. verify this case via ephemeral node owner. this
    // will happen on the callback for monitoring the lock.
    monitorActiveStatus();
    return;
  }

  String errorMessage = "Received create error from Zookeeper. code:"
      + code.toString() + " for path " + path;
  LOG.debug(errorMessage);

  if (shouldRetry(code)) {
    if (createRetryCount < maxRetryNum) {
      LOG.debug("Retrying createNode createRetryCount: " + createRetryCount);
      ++createRetryCount;
      createLockNodeAsync();
      return;
    }
    errorMessage = errorMessage
        + ". Not retrying further znode create connection errors.";
  } else if (isSessionExpired(code)) {
    // This isn't fatal - the client Watcher will re-join the election
    LOG.warn("Lock acquisition failed because session was lost");
    return;
  }

  fatalError(errorMessage);
}
 
Example 16
Source File: RecoveredAssignments.java    From zookeeper-book-example with Apache License 2.0 4 votes vote down vote up
public void processResult(int rc, 
        String path, 
        Object ctx, 
        List<String> children) {    
    switch (Code.get(rc)) { 
    case CONNECTIONLOSS:
        getWorkerAssignments(path);
        break;
    case OK:
        String worker = path.replace("/assign/", "");
        
        /*
         * If the worker is in the list of active
         * workers, then we add the tasks to the
         * assignments list. Otherwise, we need to 
         * re-assign those tasks, so we add them to
         * the list of tasks.
         */
        if(activeWorkers.contains(worker)) {
            assignments.addAll(children);
        } else {
            for( String task : children ) {
                if(!tasks.contains( task )) {
                    tasks.add( task );
                    getDataReassign( path, task );
                } else {
                    /*
                     * If the task is still in the list
                     * we delete the assignment.
                     */
                    deleteAssignment(path + "/" + task);
                }
                
                /*
                 * Delete the assignment parent. 
                 */
                deleteAssignment(path);
            }
            
        }
           
        assignedWorkers.remove(worker);
        
        /*
         * Once we have checked all assignments,
         * it is time to check the status of tasks
         */
        if(assignedWorkers.size() == 0){
            LOG.info("Getting statuses for recovery");
            getStatuses();
         }
        
        break;
    case NONODE:
        LOG.info( "No such znode exists: " + path );
        
        break;
    default:
        LOG.error("getChildren failed",  KeeperException.create(Code.get(rc), path));
        cb.recoveryComplete(RecoveryCallback.FAILED, null);
    }
}
 
Example 17
Source File: ActiveStandbyElector.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * interface implementation of Zookeeper callback for create
 */
@Override
public synchronized void processResult(int rc, String path, Object ctx,
    String name) {
  if (isStaleClient(ctx)) return;
  LOG.debug("CreateNode result: " + rc + " for path: " + path
      + " connectionState: " + zkConnectionState +
      "  for " + this);

  Code code = Code.get(rc);
  if (isSuccess(code)) {
    // we successfully created the znode. we are the leader. start monitoring
    if (becomeActive()) {
      monitorActiveStatus();
    } else {
      reJoinElectionAfterFailureToBecomeActive();
    }
    return;
  }

  if (isNodeExists(code)) {
    if (createRetryCount == 0) {
      // znode exists and we did not retry the operation. so a different
      // instance has created it. become standby and monitor lock.
      becomeStandby();
    }
    // if we had retried then the znode could have been created by our first
    // attempt to the server (that we lost) and this node exists response is
    // for the second attempt. verify this case via ephemeral node owner. this
    // will happen on the callback for monitoring the lock.
    monitorActiveStatus();
    return;
  }

  String errorMessage = "Received create error from Zookeeper. code:"
      + code.toString() + " for path " + path;
  LOG.debug(errorMessage);

  if (shouldRetry(code)) {
    if (createRetryCount < maxRetryNum) {
      LOG.debug("Retrying createNode createRetryCount: " + createRetryCount);
      ++createRetryCount;
      createLockNodeAsync();
      return;
    }
    errorMessage = errorMessage
        + ". Not retrying further znode create connection errors.";
  } else if (isSessionExpired(code)) {
    // This isn't fatal - the client Watcher will re-join the election
    LOG.warn("Lock acquisition failed because session was lost");
    return;
  }

  fatalError(errorMessage);
}