org.I0Itec.zkclient.exception.ZkNoNodeException Java Examples

The following examples show how to use org.I0Itec.zkclient.exception.ZkNoNodeException. 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: ZkClientx.java    From canal with Apache License 2.0 6 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param data
 * @param createParents if true all parent dirs are created as well and no
 * {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException if operation was interrupted, or a
 * required reconnection got interrupted
 * @throws IllegalArgumentException if called from anything except the
 * ZooKeeper event thread
 * @throws ZkException if any ZooKeeper exception occurred
 * @throws RuntimeException if any other exception occurs
 */
public String createPersistentSequential(String path, Object data, boolean createParents)
                                                                                         throws ZkInterruptedException,
                                                                                         IllegalArgumentException,
                                                                                         ZkException,
                                                                                         RuntimeException {
    try {
        return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, data, createParents);
    }
}
 
Example #2
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void fireDataChangedEvents(final String path, Set<IZkDataListener> listeners) {
    for (final IZkDataListener listener : listeners) {
        _eventThread.send(new ZkEventThread.ZkEvent("Data of " + path + " changed sent to " + listener) {

            @Override
            public void run() throws Exception {
                // reinstall watch
                exists(path, true);
                Stat stat = new Stat();
                try {
                    Object data = readData(path, stat, true);
                    listener.handleDataChange(path, data, stat);
                } catch (ZkNoNodeException e) {
                    listener.handleDataDeleted(path);
                }
            }
        });
    }
}
 
Example #3
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean deleteRecursive(String path) {
    List<String> children;
    try {
        children = getChildren(path, false);
    } catch (ZkNoNodeException e) {
        return true;
    }

    for (String subPath : children) {
        if (!deleteRecursive(path + "/" + subPath)) {
            return false;
        }
    }

    return delete(path);
}
 
Example #4
Source File: ZkClient.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public boolean delete(final String path) {
  long startT = System.nanoTime();
  try {
    try {
      retryUntilConnected(() -> {
        _connection.delete(path);
        return null;
      });

      return true;
    } catch (ZkNoNodeException e) {
      return false;
    }
  } finally {
    long endT = System.nanoTime();
    if (LOG.isTraceEnabled()) {
      LOG.trace("delete, path: {}, time: {} ns", path, (endT - startT));
    }
  }
}
 
Example #5
Source File: ZkAdapter.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Given an instance name and a datastream task name assigned to this instance, return
 * a desrialized DatastreamTask object from its JSON serialized definition in ZooKeeper.
 * @return DatastreamTask instance for the specified task name OR null if task node
 *         does not exist or is inaccessible
 */
public DatastreamTaskImpl getAssignedDatastreamTask(String instance, String taskName) {
  try {
    String content = _zkclient.ensureReadData(KeyBuilder.instanceAssignment(_cluster, instance, taskName));
    DatastreamTaskImpl task = DatastreamTaskImpl.fromJson(content);
    if (Strings.isNullOrEmpty(task.getTaskPrefix())) {
      task.setTaskPrefix(parseTaskPrefix(task.getDatastreamTaskName()));
    }

    if (Strings.isNullOrEmpty(task.getTransportProviderName())) {
      task.setTransportProviderName(_defaultTransportProviderName);
    }

    task.setZkAdapter(this);
    return task;
  } catch (ZkNoNodeException e) {
    // This can occur if there is another task assignment change in the middle of
    // handleAssignmentChange and some tasks are unassigned to the current
    // instance. In this case, we would get such exception. This is tolerable
    // because we should be receiving another AssignmentChange event right after
    // then we can dispatch the tasks based on the latest assignment data.
    LOG.warn("ZNode does not exist for instance={}, task={}, ignoring the task.", instance, taskName);
    return null;
  }
}
 
Example #6
Source File: CachedDatastreamReader.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Lookup the datastream based on its name from ZK.
 * @param datastreamName name of the datastream
 * @return the datastream object if exists; or null not exists in ZK
 */
private Datastream getDatastreamFromZk(String datastreamName) {
  String path = KeyBuilder.datastream(_cluster, datastreamName);
  if (_zkclient.exists(path)) {
    try {
      String content = _zkclient.ensureReadData(path);
      if (content != null) {
        return DatastreamUtils.fromJSON(content);
      }
    } catch (ZkNoNodeException e) {
      // This can happen when the path still exists but later deleted
      // during ensureReadData
      LOG.warn("Datastream {} is just deleted from ZK.", datastreamName);
    }
  }
  return null;
}
 
Example #7
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean delete(final String path, final int version) {
    try {
        retryUntilConnected(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                _connection.delete(path, version);
                return null;
            }
        });

        return true;
    } catch (ZkNoNodeException e) {
        return false;
    }
}
 
Example #8
Source File: ZkImpl.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Override
public Zk delete(String path, int version, Handler<AsyncResult<Void>> handler) {
    workerPool().executeBlocking(
        future -> {
            try {
                if (zookeeper.delete(path, version)) {
                    future.complete();
                } else {
                    future.fail(new ZkNoNodeException());
                }
            } catch (Throwable t) {
                future.fail(t);
            }
        },
        handler);
    return this;
}
 
Example #9
Source File: ZkClientX.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param data
 * @param createParents if true all parent dirs are created as well and no
 *                      {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException   if operation was interrupted, or a
 *                                  required reconnection got interrupted
 * @throws IllegalArgumentException if called parseFrom anything except the
 *                                  ZooKeeper event thread
 * @throws ZkException              if any ZooKeeper errors occurred
 * @throws RuntimeException         if any other errors occurs
 */
public String createPersistentSequential(String path, Object data, boolean createParents)
        throws ZkInterruptedException,
        IllegalArgumentException,
        ZkException,
        RuntimeException {
    try {
        return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, data, createParents);
    }
}
 
Example #10
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Installs a child watch for the given path.
 *
 * @param path
 * @return the current children of the path or null if the zk node with the given path doesn't exist.
 */
public List<String> watchForChilds(final String path) {
    if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
        throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
    }
    return retryUntilConnected(new Callable<List<String>>() {
        @Override
        public List<String> call() throws Exception {
            exists(path, true);
            try {
                return getChildren(path, true);
            } catch (ZkNoNodeException e) {
                // ignore, the "exists" watch will listen for the parent node to appear
            }
            return null;
        }
    });
}
 
Example #11
Source File: ZkClientx.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param data
 * @param createParents if true all parent dirs are created as well and no
 * {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException if operation was interrupted, or a
 * required reconnection got interrupted
 * @throws IllegalArgumentException if called from anything except the
 * ZooKeeper event thread
 * @throws ZkException if any ZooKeeper exception occurred
 * @throws RuntimeException if any other exception occurs
 */
public String createPersistentSequential(String path, Object data, boolean createParents)
                                                                                         throws ZkInterruptedException,
                                                                                         IllegalArgumentException,
                                                                                         ZkException,
                                                                                         RuntimeException {
    try {
        return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, data, createParents);
    }
}
 
Example #12
Source File: ZkTopicStore.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Override
public Future<Topic> read(TopicName topicName) {
    Promise<Topic> handler = Promise.promise();
    String topicPath = getTopicPath(topicName);
    zk.getData(topicPath, result -> {
        final AsyncResult<Topic> fut;
        if (result.succeeded()) {
            fut = Future.succeededFuture(TopicSerialization.fromJson(result.result()));
        } else {
            if (result.cause() instanceof ZkNoNodeException) {
                fut = Future.succeededFuture(null);
            } else {
                fut = result.map((Topic) null);
            }
        }
        handler.handle(fut);
    });
    return handler.future();
}
 
Example #13
Source File: ZooKeeperMetaManager.java    From canal with Apache License 2.0 6 votes vote down vote up
public PositionRange getLastestBatch(ClientIdentity clientIdentity) {
    String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(),
        clientIdentity.getClientId());
    List<String> nodes = null;
    try {
        nodes = zkClientx.getChildren(path);
    } catch (ZkNoNodeException e) {
        // ignore
    }

    if (CollectionUtils.isEmpty(nodes)) {
        return null;
    }
    // 找到最大的Id
    ArrayList<Long> batchIds = new ArrayList<Long>(nodes.size());
    for (String batchIdString : nodes) {
        batchIds.add(Long.valueOf(batchIdString));
    }
    Long maxBatchId = Collections.max(batchIds);
    PositionRange result = getBatch(clientIdentity, maxBatchId);
    if (result == null) { // 出现为null,说明zk节点有变化,重新获取
        return getLastestBatch(clientIdentity);
    } else {
        return result;
    }
}
 
Example #14
Source File: ZooKeeperMetaManager.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
public PositionRange getFirstBatch(ClientIdentity clientIdentity) {
    String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(),
        clientIdentity.getClientId());
    List<String> nodes = null;
    try {
        nodes = zkClientx.getChildren(path);
    } catch (ZkNoNodeException e) {
        // ignore
    }

    if (CollectionUtils.isEmpty(nodes)) {
        return null;
    }
    // 找到最小的Id
    ArrayList<Long> batchIds = new ArrayList<Long>(nodes.size());
    for (String batchIdString : nodes) {
        batchIds.add(Long.valueOf(batchIdString));
    }
    Long minBatchId = Collections.min(batchIds);
    PositionRange result = getBatch(clientIdentity, minBatchId);
    if (result == null) { // 出现为null,说明zk节点有变化,重新获取
        return getFirstBatch(clientIdentity);
    } else {
        return result;
    }
}
 
Example #15
Source File: ZooKeeperMetaManager.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
public PositionRange getLastestBatch(ClientIdentity clientIdentity) {
    String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(),
        clientIdentity.getClientId());
    List<String> nodes = null;
    try {
        nodes = zkClientx.getChildren(path);
    } catch (ZkNoNodeException e) {
        // ignore
    }

    if (CollectionUtils.isEmpty(nodes)) {
        return null;
    }
    // 找到最大的Id
    ArrayList<Long> batchIds = new ArrayList<Long>(nodes.size());
    for (String batchIdString : nodes) {
        batchIds.add(Long.valueOf(batchIdString));
    }
    Long maxBatchId = Collections.max(batchIds);
    PositionRange result = getBatch(clientIdentity, maxBatchId);
    if (result == null) { // 出现为null,说明zk节点有变化,重新获取
        return getLastestBatch(clientIdentity);
    } else {
        return result;
    }
}
 
Example #16
Source File: ZooKeeperMetaManager.java    From canal with Apache License 2.0 6 votes vote down vote up
public PositionRange getFirstBatch(ClientIdentity clientIdentity) {
    String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(),
        clientIdentity.getClientId());
    List<String> nodes = null;
    try {
        nodes = zkClientx.getChildren(path);
    } catch (ZkNoNodeException e) {
        // ignore
    }

    if (CollectionUtils.isEmpty(nodes)) {
        return null;
    }
    // 找到最小的Id
    ArrayList<Long> batchIds = new ArrayList<Long>(nodes.size());
    for (String batchIdString : nodes) {
        batchIds.add(Long.valueOf(batchIdString));
    }
    Long minBatchId = Collections.min(batchIds);
    PositionRange result = getBatch(clientIdentity, minBatchId);
    if (result == null) { // 出现为null,说明zk节点有变化,重新获取
        return getFirstBatch(clientIdentity);
    } else {
        return result;
    }
}
 
Example #17
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Installs a child watch for the given path.
 *
 * @param path
 * @return the current children of the path or null if the zk node with the given path doesn't exist.
 */
public List<String> watchForChilds(final String path) {
    if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
        throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
    }
    return retryUntilConnected(new Callable<List<String>>() {
        @Override
        public List<String> call() throws Exception {
            exists(path, true);
            try {
                return getChildren(path, true);
            } catch (ZkNoNodeException e) {
                // ignore, the "exists" watch will listen for the parent node to appear
            }
            return null;
        }
    });
}
 
Example #18
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean delete(final String path, final int version) {
    try {
        retryUntilConnected(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                _connection.delete(path, version);
                return null;
            }
        });

        return true;
    } catch (ZkNoNodeException e) {
        return false;
    }
}
 
Example #19
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void fireDataChangedEvents(final String path, Set<IZkDataListener> listeners) {
    for (final IZkDataListener listener : listeners) {
        _eventThread.send(new ZkEventThread.ZkEvent("Data of " + path + " changed sent to " + listener) {

            @Override
            public void run() throws Exception {
                // reinstall watch
                exists(path, true);
                Stat stat = new Stat();
                try {
                    Object data = readData(path, stat, true);
                    listener.handleDataChange(path, data, stat);
                } catch (ZkNoNodeException e) {
                    listener.handleDataDeleted(path);
                }
            }
        });
    }
}
 
Example #20
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean deleteRecursive(String path) {
    List<String> children;
    try {
        children = getChildren(path, false);
    } catch (ZkNoNodeException e) {
        return true;
    }

    for (String subPath : children) {
        if (!deleteRecursive(path + "/" + subPath)) {
            return false;
        }
    }

    return delete(path);
}
 
Example #21
Source File: ZkUtils.java    From kangaroo with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
List<String> getChildrenParentMayNotExist(String path) {
    try {
        return client.getChildren(path);
    } catch (final ZkNoNodeException e) {
        return Lists.newArrayList();
    }
}
 
Example #22
Source File: ZooKeeperMetaManager.java    From canal with Apache License 2.0 5 votes vote down vote up
public Map<Long, PositionRange> listAllBatchs(ClientIdentity clientIdentity) {
    String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(),
        clientIdentity.getClientId());
    List<String> nodes = null;
    try {
        nodes = zkClientx.getChildren(path);
    } catch (ZkNoNodeException e) {
        // ignore
    }

    if (CollectionUtils.isEmpty(nodes)) {
        return Maps.newHashMap();
    }
    // 找到最大的Id
    ArrayList<Long> batchIds = new ArrayList<Long>(nodes.size());
    for (String batchIdString : nodes) {
        batchIds.add(Long.valueOf(batchIdString));
    }

    Collections.sort(batchIds); // 从小到大排序
    Map<Long, PositionRange> positionRanges = Maps.newLinkedHashMap();
    for (Long batchId : batchIds) {
        PositionRange result = getBatch(clientIdentity, batchId);
        if (result == null) {// 出现为null,说明zk节点有变化,重新获取
            return listAllBatchs(clientIdentity);
        } else {
            positionRanges.put(batchId, result);
        }
    }

    return positionRanges;
}
 
Example #23
Source File: ZooKeeperMetaManager.java    From canal with Apache License 2.0 5 votes vote down vote up
public void updateCursor(ClientIdentity clientIdentity, Position position) throws CanalMetaManagerException {
    String path = ZookeeperPathUtils.getCursorPath(clientIdentity.getDestination(), clientIdentity.getClientId());
    byte[] data = JsonUtils.marshalToByte(position, SerializerFeature.WriteClassName);
    try {
        zkClientx.writeData(path, data);
    } catch (ZkNoNodeException e) {
        zkClientx.createPersistent(path, data, true);// 第一次节点不存在,则尝试重建
    }
}
 
Example #24
Source File: ZooKeeperLogPositionManager.java    From canal with Apache License 2.0 5 votes vote down vote up
@Override
public void persistLogPosition(String destination, LogPosition logPosition) throws CanalParseException {
    String path = ZookeeperPathUtils.getParsePath(destination);
    byte[] data = JsonUtils.marshalToByte(logPosition);
    try {
        zkClientx.writeData(path, data);
    } catch (ZkNoNodeException e) {
        zkClientx.createPersistent(path, data, true);
    }
}
 
Example #25
Source File: ZKOffsetGetter.java    From kmanager with Apache License 2.0 5 votes vote down vote up
private Tuple2<String, Stat> readZkData(String path) {
	Tuple2<String, Stat> offset_stat = null;
	try {
		offset_stat = ZKUtils.getZKUtilsFromKafka().readData(path);
	} catch (ZkNoNodeException znne) {
		// TODO no offset record in zk?
	}
	return offset_stat;
}
 
Example #26
Source File: ZkclientZookeeperClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
public List<String> getChildren(String path) {
    try {
        return client.getChildren(path);
    } catch (ZkNoNodeException e) {
        return null;
    }
}
 
Example #27
Source File: ZkClientx.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
    * 创建一个持久的顺序节点
    */
public String createPersistentSequential(String path, boolean createParents)
		throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
       try {
           return create(path, null, CreateMode.PERSISTENT_SEQUENTIAL);
       } catch (ZkNoNodeException e) {
           if (!createParents) {
               throw e;
           }
           String parentDir = path.substring(0, path.lastIndexOf('/'));
           createPersistent(parentDir, createParents);
           return createPersistentSequential(path, createParents);
       }
   }
 
Example #28
Source File: ZkClientx.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String createPersistentSequential(String path, Object data, boolean createParents)
throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
     try {
         return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
     } catch (ZkNoNodeException e) {
         if (!createParents) {
             throw e;
         }
         String parentDir = path.substring(0, path.lastIndexOf('/'));
         createPersistent(parentDir, createParents);
         return createPersistentSequential(path, data, createParents);
     }
 }
 
Example #29
Source File: ZkTopicStore.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> delete(TopicName topicName) {
    Promise<Void> handler = Promise.promise();
    // TODO pass a non-zero version
    String topicPath = getTopicPath(topicName);
    LOGGER.debug("delete znode {}", topicPath);
    zk.delete(topicPath, -1, result -> {
        if (result.failed() && result.cause() instanceof ZkNoNodeException) {
            handler.handle(Future.failedFuture(new NoSuchEntityExistsException()));
        } else {
            handler.handle(result);
        }
    });
    return handler.future();
}
 
Example #30
Source File: ZkclientZookeeperClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public List<String> getChildren(String path) {
	try {
		return client.getChildren(path);
       } catch (ZkNoNodeException e) {
           return null;
       }
}