Java Code Examples for org.apache.zookeeper.ZooKeeper#delete()

The following examples show how to use org.apache.zookeeper.ZooKeeper#delete() . 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: ServiceUnitZkUtils.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * cleanupSingleNamespaceNode is only called when the NamespaceService is initialized. So, no need for
 * synchronization.
 *
 * @throws Exception
 */
private static final void cleanupSingleNamespaceNode(ZooKeeper zkc, String path, String selfBrokerUrl)
        throws Exception {
    String brokerUrl = null;
    try {
        byte[] data = zkc.getData(path, false, null);
        if (data == null || data.length == 0) {
            // skip, ephemeral node will not have zero byte
            return;
        }

        NamespaceEphemeralData zdata = jsonMapper.readValue(data, NamespaceEphemeralData.class);
        brokerUrl = zdata.getNativeUrl();

        if (selfBrokerUrl.equals(brokerUrl)) {
            // The znode indicate that the owner is this instance while this instance was just started before
            // acquiring any namespaces yet
            // Hence, the znode must have been created previously by this instance and needs to be cleaned up
            zkc.delete(path, -1);
        }
    } catch (NoNodeException nne) {
        // The node may expired before this instance tries to get or delete it from ZK. It is OK and considered as
        // NOOP.
    }
}
 
Example 2
Source File: ZookeeperResourceTest.java    From spring-zookeeper with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void insertData2Zk() throws KeeperException, InterruptedException, IOException {
    ZookeeperConfigurer zkConf = (ZookeeperConfigurer) ctx.getBean("zkPropConfigurer");
    ZookeeperResource zkResource = (ZookeeperResource) zkConf.getZkResoucre();
    ZooKeeper zk = zkResource.getZk();
    try {
        zk.delete("/cn_dev", -1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String fileName = "/zk_cnfig_cn_test.txt";
    String fileContent = getFileContent(fileName);
    zk.create("/cn_dev", fileContent.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
 
Example 3
Source File: ZkUtils.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public static void rmr(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
  List<String> children = zooKeeper.getChildren(path, false);
  for (String c : children) {
    rmr(zooKeeper, path + "/" + c);
  }
  zooKeeper.delete(path, -1);
}
 
Example 4
Source File: MasterBasedDistributedLayoutFactoryTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private void rmr(ZooKeeper zooKeeper, String storagePath) throws KeeperException, InterruptedException {
  Stat stat = zooKeeper.exists(storagePath, false);
  if (stat == null) {
    return;
  }
  List<String> children = zooKeeper.getChildren(storagePath, false);
  for (String s : children) {
    rmr(zooKeeper, storagePath + "/" + s);
  }
  zooKeeper.delete(storagePath, -1);
}
 
Example 5
Source File: SafeModeTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static void rm(ZooKeeper zk, String path) throws KeeperException, InterruptedException {
  List<String> children = zk.getChildren(path, false);
  for (String c : children) {
    rm(zk, path + "/" + c);
  }
  zk.delete(path, -1);
}
 
Example 6
Source File: ZookeeperClusterStatusTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static void rmr(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
  List<String> children = zooKeeper.getChildren(path, false);
  for (String c : children) {
    rmr(zooKeeper, path + "/" + c);
  }
  zooKeeper.delete(path, -1);
}
 
Example 7
Source File: BlurUtil.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public static void removeAll(ZooKeeper zooKeeper, String path) throws KeeperException, InterruptedException {
  List<String> list = zooKeeper.getChildren(path, false);
  for (String p : list) {
    removeAll(zooKeeper, path + "/" + p);
  }
  LOG.info("Removing path [{0}]", path);
  zooKeeper.delete(path, -1);
}
 
Example 8
Source File: DistributedQueue.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
private static void consume(ZooKeeper zk) throws KeeperException, InterruptedException {

        List<String> list = zk.getChildren("/distributedQueue", true);
        if (list.size() > 0) {

            String subPath = list.get(0);
            String zNode = "/distributedQueue/" + subPath;
            System.out.println("Get the data:\t" + new String(zk.getData(zNode, false, null),
                    StandardCharsets.UTF_8) + "\tfrom " + zNode);

            zk.delete(zNode, 0);
        } else {
            System.out.println("No node to consume.");
        }
    }
 
Example 9
Source File: TestRoundRobinJedisPool.java    From jodis with MIT License 5 votes vote down vote up
private void removeNode(String name) throws InterruptedException, KeeperException, IOException {
    ZooKeeper zk = new ZooKeeper("localhost:" + zkPort, 5000, null);
    try {
        zk.delete(zkProxyDir + "/" + name, -1);
    } finally {
        zk.close();
    }
}
 
Example 10
Source File: ZKTools.java    From uncode-schedule with Apache License 2.0 5 votes vote down vote up
public static void deleteTree(ZooKeeper zk, String path) throws Exception {
  //    String[] list = getSortedTree(zk, path);
  //    for (int i = list.length - 1; i >= 0; i--) {
  //      zk.delete(list[i], -1);
  //    }

  List<String> tree = listSubTreeBFS(zk, path);
  for (int i = tree.size() - 1; i >= 0; i--) { //@wjw_note: 必须倒序!
    zk.delete(tree.get(i), -1);
  }
}
 
Example 11
Source File: LocalZooKeeperConnectionService.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static void deleteIfExists(ZooKeeper zk, String path, int version)
        throws KeeperException, InterruptedException {
    try {
        zk.delete(path, version);
    } catch (NoNodeException e) {
        // OK
        LOG.debug("Delete skipped for non-existing znode: path={}", path);
    }
}
 
Example 12
Source File: ResourceClaim.java    From azeroth with Apache License 2.0 5 votes vote down vote up
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 13
Source File: ZKTools.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void deleteTree(ZooKeeper zk,String path) throws Exception{
 String[] list = getTree(zk,path);
 for(int i= list.length -1;i>=0; i--){
  zk.delete(list[i],-1);
 }
}
 
Example 14
Source File: IndexerIT.java    From hbase-indexer with Apache License 2.0 4 votes vote down vote up
private void cleanZooKeeper(String zkConnectString, String rootToDelete) throws Exception {
    int sessionTimeout = 10000;

    ZooKeeper zk = new ZooKeeper(zkConnectString, sessionTimeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.Disconnected) {
                System.err.println("ZooKeeper Disconnected.");
            } else if (event.getState() == Event.KeeperState.Expired) {
                System.err.println("ZooKeeper session expired.");
            }
        }
    });

    long waitUntil = System.currentTimeMillis() + sessionTimeout;
    while (zk.getState() != CONNECTED && waitUntil > System.currentTimeMillis()) {
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            break;
        }
    }

    if (zk.getState() != CONNECTED) {
        throw new RuntimeException("Failed to connect to ZK within " + sessionTimeout + "ms.");
    }

    if (zk.exists(rootToDelete, false) != null) {
        List<String> paths = new ArrayList<String>();
        collectChildren(rootToDelete, zk, paths);
        paths.add(rootToDelete);

        for (String path : paths) {
            zk.delete(path, -1, null, null);
        }

        // The above deletes are async, wait for them to be finished
        long startWait = System.currentTimeMillis();
        while (zk.exists(rootToDelete, null) != null) {
            Thread.sleep(5);

            if (System.currentTimeMillis() - startWait > 120000) {
                throw new RuntimeException("State was not cleared in ZK within the expected timeout");
            }
        }
    }

    zk.close();
}
 
Example 15
Source File: ZooKeeperOutput.java    From envelope with Apache License 2.0 4 votes vote down vote up
@Override
public void applyRandomMutations(List<Row> planned) throws Exception {
  if (planned.size() > 1000) {
    throw new RuntimeException(
        "ZooKeeper output does not support applying more than 1000 mutations at a time. " +
        "This is to prevent misuse of ZooKeeper as a regular data store. " + 
        "Do not use ZooKeeper for storing anything more than small pieces of metadata.");
  }

  ZooKeeper zk;
  try {
    zk = connection.getZooKeeper();
  } catch (Exception e) {
    throw new RuntimeException("Could not connect to ZooKeeper output", e);
  }
  
  for (Row plan : planned) {
    if (plan.schema() == null) {
      throw new RuntimeException("Mutation row provided to ZooKeeper output must contain a schema");
    }
    
    MutationType mutationType = PlannerUtils.getMutationType(plan);
    plan = PlannerUtils.removeMutationTypeField(plan);
    
    Row key = RowUtils.subsetRow(plan, SchemaUtils.subsetSchema(plan.schema(), keyFieldNames));
    String znode = znodesForFilter(zk, key).iterator().next(); // There can only be one znode per full key
    byte[] value = serializeRow(RowUtils.subsetRow(plan, SchemaUtils.subtractSchema(plan.schema(), keyFieldNames)));
    
    switch (mutationType) {
      case DELETE:
        zk.delete(znode, -1);
        break;
      case UPSERT:
        prepareZnode(zk, znode);
        zk.setData(znode, value, -1);
        break;
      default:
        throw new RuntimeException("ZooKeeper output does not support mutation type: " + PlannerUtils.getMutationType(plan));
    }
  }
}
 
Example 16
Source File: BlurUtil.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
public static void unlockForSafeMode(ZooKeeper zookeeper, String lockPath) throws InterruptedException,
    KeeperException {
  zookeeper.delete(lockPath, -1);
  LOG.info("Lock released.");
}
 
Example 17
Source File: ConfigurationGenerator.java    From examples with Apache License 2.0 4 votes vote down vote up
private ConfigurationGenerator() {
    try {
        ZooKeeper zk = new ZooKeeper(Constants.ZOOKEEPER_CONNECTION_STRING, 5000, this);
        // Wait for the zookeeper servers to get ready... which can several seconds when
        // using docker
        while(zk.getState() != ZooKeeper.States.CONNECTED) {
            synchronized (mutex) {
                mutex.wait(5000);
            }
        }

        // With docker we will always need to create the root, but with reconfiguration
        // you might first need to lookup the currently saved configuration in zookeeper
        Stat s = zk.exists(Constants.CONFIGURATION_PATH, false);
        int version = configVersion.get();
        if (s == null) {
            zk.create(Constants.CONFIGURATION_PATH,
                      Integer.toString(version).getBytes(),
                      Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        else {
            byte[] rawData = zk.getData(Constants.CONFIGURATION_PATH, false, s);
            configVersion.set(new Integer(new String(rawData)).intValue());
        }

        // Every 5-10 seconds, create a new configuration
        Random rand = new Random();
        while (true) {
            synchronized (mutex) {
                mutex.wait(5000 + rand.nextInt(5000));
            }

            version = configVersion.incrementAndGet();
            System.out.println("ConfigurationGenerator: Updating version to " + version);
            // the order of these two calls is important
            zk.create(Constants.CONFIGURATION_PATH + "/" + version,
                      ConfigurationGenerator.createConfiguration(version).encode().getBytes(),
                      Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zk.setData(Constants.CONFIGURATION_PATH,
                       Integer.toString(version).getBytes(),
                       version - 1);
            // Delete configuration versions while keeping one prior version.
            if(version > 2) {
                zk.delete(Constants.CONFIGURATION_PATH + "/" + (version - 2), -1);
            }
        }
    } catch (IOException | InterruptedException | KeeperException e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: ZKTools.java    From uncode-schedule with GNU General Public License v2.0 4 votes vote down vote up
public static void deleteTree(ZooKeeper zk,String path) throws Exception{
 String[] list = getTree(zk,path);
 for(int i= list.length -1;i>=0; i--){
  zk.delete(list[i],-1);
 }
}
 
Example 19
Source File: ZKTools.java    From tbschedule with Apache License 2.0 4 votes vote down vote up
public static void deleteTree(ZooKeeper zk, String path) throws Exception {
    String[] list = getTree(zk, path);
    for (int i = list.length - 1; i >= 0; i--) {
        zk.delete(list[i], -1);
    }
}
 
Example 20
Source File: ZookeeperTest.java    From java-study with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	// 创建一个与服务器的连接
	 zk = new ZooKeeper(url , 
			 CONNECTION_TIMEOUT, new Watcher() { 
	            // 监控所有被触发的事件
	            public void process(WatchedEvent event) {
	                System.out.println(event.getPath()+"已经触发了" + event.getType() + "事件!"); 
	            } 
	        }); 
	 
	 /*
	  * 创建一个给定的目录节点 path, 并给它设置数据,
	  * CreateMode 标识有四种形式的目录节点,分别是
	  *  PERSISTENT:持久化目录节点,这个目录节点存储的数据不会丢失;
	  *  PERSISTENT_SEQUENTIAL:顺序自动编号的目录节点,这种目录节点会根据当前已近存在的节点数自动加 1,
	  *  然后返回给客户端已经成功创建的目录节点名;
	  *  EPHEMERAL:临时目录节点,一旦创建这个节点的客户端与服务器端口也就是 session 超时,这种节点会被自动删除;
	  *  EPHEMERAL_SEQUENTIAL:临时自动编号节点
	  */
	 
	 // 创建一个父级目录节点
	 if(zk.exists("/test", true)==null){
		 //参数说明:目录,参数,参数权限,节点类型
		 zk.create("/test", "data1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 
	 }
	 if(zk.exists("/test/test1", true)==null){
		 // 创建一个子目录节点
		 zk.create("/test/test1", "data2".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); 
	 }
	 
	 System.out.println("="+new String(zk.getData("/test",false,null))); 
	 // 取出子目录节点列表
	 System.out.println("=="+zk.getChildren("/test",true)); 
	
	 if(zk.exists("/test/test1", true)!=null){
		 // 修改子目录节点数据
		 zk.setData("/test/test1","testOne".getBytes(),-1); 
	 }
	 System.out.println("目录节点状态:["+zk.exists("/test",true)+"]"); 
	 if(zk.exists("/test/test1", true)!=null){
	  // 创建另外一个子目录节点
	  zk.create("/test/test2", "test2".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); 
	 }
	 System.out.println("==="+new String(zk.getData("/test/test2",true,null))); 

	 /*
	  * 删除 path 对应的目录节点,version 为 -1 可以匹配任何版本,也就删除了这个目录节点所有数据
	  */
	 // 删除子目录节点
	 zk.delete("/test/test2",-1); 
	 zk.delete("/test/test1",-1); 
	 
	 // 删除父目录节点
	 zk.delete("/test",-1); 
	 // 关闭连接
	 zk.close();
}