Example usage for org.apache.zookeeper ZooKeeper delete

List of usage examples for org.apache.zookeeper ZooKeeper delete

Introduction

In this page you can find the example usage for org.apache.zookeeper ZooKeeper delete.

Prototype

public void delete(final String path, int version, VoidCallback cb, Object ctx) 

Source Link

Document

The asynchronous version of delete.

Usage

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

private void removeNodeUnsafe(final String path, final Callback<None> callback, final int count) {
    final ZooKeeper zk = zk();

    final AsyncCallback.VoidCallback deleteCallback = new AsyncCallback.VoidCallback() {
        @Override/*from   w w w.ja  v  a  2 s .  c om*/
        public void processResult(int rc, String path, Object ctx) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(None.none());
                break;
            case BADVERSION:
                // Need to retry
                if (count < MAX_RETRIES) {
                    LOG.info("removeNodeUnsafe: retrying after ignoring BADVERSION for {}", path);
                    removeNodeUnsafe(path, callback, count + 1);
                } else {
                    callback.onError(KeeperException.create(code));
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };

    final AsyncCallback.StatCallback existsCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                zk.delete(path, stat.getVersion(), deleteCallback, null);
                break;
            case NONODE:
                callback.onSuccess(None.none());
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };

    try {
        zk.exists(path, false, existsCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.ngdata.hbaseindexer.indexer.IndexerIT.java

License:Apache License

private void cleanZooKeeper(String zkConnectString, String rootToDelete) throws Exception {
    int sessionTimeout = 10000;

    ZooKeeper zk = new ZooKeeper(zkConnectString, sessionTimeout, new Watcher() {
        @Override/*from  w  ww  .  j  a  v  a 2 s.  c  o  m*/
        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();
}

From source file:com.proofpoint.zookeeper.ZookeeperClient.java

License:Apache License

@Override
public void delete(final String path) throws Exception {
    preconditionNotWatched();/*ww w .j a  va2 s  . co  m*/

    if (inBackground) {
        RetryHandler.Call<Void> backgroundCall = new RetryHandler.Call<Void>() {
            @Override
            public Void call(ZooKeeper client, final RetryHandler retryHandler) {
                client.delete(path, dataVersion, new AsyncCallback.VoidCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx) {
                        if (retryHandler.okToContinue(rc)) {
                            eventQueue.postEvent(new ZookeeperEvent(ZookeeperEvent.Type.DELETE, rc, path, ctx,
                                    null, null, null, null, key));
                        }
                    }
                }, context);
                return null;
            }
        };
        RetryHandler.makeAndStart(this, retryPolicy, backgroundCall);
    } else {
        RetryHandler.Call<Void> backgroundCall = new RetryHandler.Call<Void>() {
            @Override
            public Void call(ZooKeeper client, RetryHandler<Void> voidRetryHandler) throws Exception {
                client.delete(path, dataVersion);

                // watchers aren't necessarily called on local deletes
                eventQueue.postEvent(new ZookeeperEvent(ZookeeperEvent.Type.DELETE,
                        KeeperException.Code.OK.intValue(), path, context, null, null, null, null, key));
                return null;
            }
        };
        RetryHandler.makeAndStart(this, retryPolicy, backgroundCall);
    }
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Delete the given <i>path</i> from zookeeper.
 *
 * @param zk/*from ww w.java 2s.c om*/
 *          zookeeper client
 * @param path
 *          path to delete
 * @param version
 *          version used to set data
 * @return future representing the version after this operation.
 */
public static Future<Void> zkDelete(ZooKeeper zk, String path, ZkVersion version) {
    final Promise<Void> promise = new Promise<Void>();
    zk.delete(path, version.getZnodeVersion(), new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.updateIfEmpty(new Return<Void>(null));
                return;
            }
            promise.updateIfEmpty(new Throw<Void>(KeeperException.create(KeeperException.Code.get(rc))));
            return;
        }
    }, null);
    return promise;
}

From source file:org.apache.bookkeeper.zookeeper.BkZooKeeperClient.java

License:Apache License

@Override
public void delete(final String path, final int version, final VoidCallback cb, final Object context) {
    final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, deleteStats) {

        final VoidCallback deleteCb = new VoidCallback() {

            @Override//ww  w. ja va  2s  . c  om
            public void processResult(int rc, String path, Object ctx) {
                BkZooWorker worker = (BkZooWorker) ctx;
                if (allowRetry(worker, rc)) {
                    backOffAndRetry(that, worker.nextRetryWaitTime());
                } else {
                    cb.processResult(rc, path, context);
                }
            }

        };

        @Override
        void zkRun() {
            ZooKeeper zkHandle = zk.get();
            if (null == zkHandle) {
                BkZooKeeperClient.super.delete(path, version, deleteCb, worker);
            } else {
                zkHandle.delete(path, version, deleteCb, worker);
            }
        }

        @Override
        public String toString() {
            return String.format("delete (%s, version = %d)", path, version);
        }
    };
    // execute it immediately
    proc.run();
}

From source file:org.apache.bookkeeper.zookeeper.ZooKeeperClient.java

License:Apache License

@Override
public void delete(final String path, final int version, final VoidCallback cb, final Object context) {
    final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, deleteStats) {

        final VoidCallback deleteCb = new VoidCallback() {

            @Override//from w w w . j ava 2 s.c  o  m
            public void processResult(int rc, String path, Object ctx) {
                ZooWorker worker = (ZooWorker) ctx;
                if (allowRetry(worker, rc)) {
                    backOffAndRetry(that, worker.nextRetryWaitTime());
                } else {
                    cb.processResult(rc, path, context);
                }
            }

        };

        @Override
        void zkRun() {
            ZooKeeper zkHandle = zk.get();
            if (null == zkHandle) {
                ZooKeeperClient.super.delete(path, version, deleteCb, worker);
            } else {
                zkHandle.delete(path, version, deleteCb, worker);
            }
        }

        @Override
        public String toString() {
            return String.format("delete (%s, version = %d)", path, version);
        }
    };
    // execute it immediately
    proc.run();
}

From source file:org.apache.camel.component.zookeeper.ZookeeperProducer.java

License:Apache License

private void asynchronouslyDeleteNode(ZooKeeper connection, ProductionContext context) {
    if (log.isDebugEnabled()) {
        log.debug(format("Deleting node '%s', not waiting for confirmation", context.node));
    }/*from ww  w.j  a v a  2s .  com*/
    connection.delete(context.node, context.version, new AsyncDeleteCallback(), context);

}

From source file:org.apache.distributedlog.util.Utils.java

License:Apache License

/**
 * Delete the given <i>path</i> from zookeeper.
 *
 * @param zk//from   w ww.j a  v a  2 s .com
 *          zookeeper client
 * @param path
 *          path to delete
 * @param version
 *          version used to set data
 * @return future representing the version after this operation.
 */
public static CompletableFuture<Void> zkDelete(ZooKeeper zk, String path, LongVersion version) {
    final CompletableFuture<Void> promise = new CompletableFuture<Void>();
    zk.delete(path, (int) version.getLongVersion(), new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.complete(null);
                return;
            }
            promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
            return;
        }
    }, null);
    return promise;
}

From source file:org.apache.distributedlog.util.Utils.java

License:Apache License

/**
 * Delete the given <i>path</i> from zookeeper.
 *
 * @param zkc//from  w w w.  jav a  2  s  .c  om
 *          zookeeper client
 * @param path
 *          path to delete
 * @param version
 *          version used to set data
 * @return future representing if the delete is successful. Return true if the node is deleted,
 * false if the node doesn't exist, otherwise future will throw exception
 *
 */
public static CompletableFuture<Boolean> zkDeleteIfNotExist(ZooKeeperClient zkc, String path,
        LongVersion version) {
    ZooKeeper zk;
    try {
        zk = zkc.get();
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        return FutureUtils.exception(zkException(e, path));
    } catch (InterruptedException e) {
        return FutureUtils.exception(zkException(e, path));
    }
    final CompletableFuture<Boolean> promise = new CompletableFuture<Boolean>();
    zk.delete(path, (int) version.getLongVersion(), new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.complete(true);
            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                promise.complete(false);
            } else {
                promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
            }
        }
    }, null);
    return promise;
}

From source file:org.lilyproject.hadooptestfw.CleanupUtil.java

License:Apache License

public void cleanZooKeeper() throws Exception {
    int sessionTimeout = 10000;

    ZooKeeper zk = new ZooKeeper(zkConnectString, sessionTimeout, new Watcher() {
        @Override//w ww. j  a  v a 2  s  .c  o m
        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("/lily", false) != null) {
        System.out.println("----------------- Clearing '/lily' node in ZooKeeper -------------------");

        List<String> paths = new ArrayList<String>();
        collectChildren("/lily", zk, paths);
        paths.add("/lily");

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

        long startWait = System.currentTimeMillis();
        while (zk.exists("/lily", null) != null) {
            Thread.sleep(5);

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

        System.out.println("Deleted " + paths.size() + " paths from ZooKeeper");
        System.out.println("------------------------------------------------------------------------");
    }

    zk.close();
}