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) throws InterruptedException, KeeperException 

Source Link

Document

Delete the node with the given path.

Usage

From source file:com.andyadc.menagerie.locks.ReentrantZkLock.java

License:Apache License

/**
 * Acquires the lock only if it is free at the time of invocation.
 * <p><p>//w w  w.  j a  v  a2  s .  c  om
 * Note: If the ZooKeeper Session expires while this thread is processing, nothing is required to happen.
 *
 * @return true if the lock has been acquired, false otherwise
 * @throws RuntimeException wrapping :
 *                          <ul>
 *                          <li>{@link KeeperException} if there is trouble
 *                          processing a request with the ZooKeeper servers.
 *                          <li> {@link InterruptedException} if there is an error communicating between the ZooKeeper client and servers.
 *                          </ul>
 * @inheritDoc
 */
@Override
public final boolean tryLock() {
    if (checkReentrancy())
        return true;
    ZooKeeper zk = zkSessionManager.getZooKeeper();
    try {
        String lockNode = zk.create(getBaseLockPath(), emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL);

        //try to determine its position in the queue
        boolean lockAcquired = tryAcquireDistributed(zk, lockNode, false);
        if (!lockAcquired) {
            //we didn't get the lock, so return false
            zk.delete(lockNode, -1);
            return false;
        } else {
            //we have the lock, so it goes on the queue
            locks.set(new LockHolder(lockNode));
            return true;
        }
    } catch (KeeperException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.andyadc.menagerie.locks.ReentrantZkLock.java

License:Apache License

/**
 * Acquires the lock only if it is free within the given waiting time and the current thread has not been
 * interrupted.//from   ww  w  .  j  a v  a  2 s .co m
 * <p><p>
 * Note: If the ZooKeeper Session expires while this thread is waiting, an {@link InterruptedException} will be
 * thrown.
 *
 * @param time the maximum time to wait, in milliseconds
 * @param unit the TimeUnit to use
 * @return true if the lock is acquired before the timeout expires
 * @throws InterruptedException if one of the four following conditions hold:
 *                              <ol>
 *                              <li value="1">The Thread is interrupted upon entry to the method
 *                              <li value="2">Another thread interrupts this thread while it is waiting to acquire the lock
 *                              <li value="3">There is a communication problem between the ZooKeeper client and the ZooKeeper server.
 *                              <li value="4">The ZooKeeper session expires and invalidates this lock.
 *                              </ol>
 * @inheritDoc
 * @see #tryLock(long, TimeUnit)
 */
@Override
public final boolean tryLock(long time, TimeUnit unit) throws InterruptedException {

    if (Thread.interrupted())
        throw new InterruptedException();

    if (checkReentrancy())
        return true;
    ZooKeeper zk = zkSessionManager.getZooKeeper();
    //add a connection listener
    setConnectionListener();
    String lockNode;
    try {
        lockNode = zk.create(getBaseLockPath(), emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL);

        while (true) {
            if (Thread.interrupted()) {
                zk.delete(lockNode, -1);
                throw new InterruptedException();
            } else if (broken) {
                throw new InterruptedException("The ZooKeeper Session expired and invalidated this lock");
            }
            boolean localAcquired = localLock.tryLock(time, unit);
            try {
                if (!localAcquired) {
                    //delete the lock node and return false
                    zk.delete(lockNode, -1);
                    return false;
                }
                //ask ZooKeeper for the lock
                boolean acquiredLock = tryAcquireDistributed(zk, lockNode, true);

                if (!acquiredLock) {
                    //we don't have the lock, so we need to wait for our watcher to fire
                    boolean alerted = condition.await(time, unit);
                    if (!alerted) {
                        //we timed out, so delete the node and return false
                        zk.delete(lockNode, -1);
                        return false;
                    }
                } else {
                    //we have the lock, so return happy
                    locks.set(new LockHolder(lockNode));
                    return true;
                }
            } finally {
                localLock.unlock();
            }
        }
    } catch (KeeperException e) {
        throw new RuntimeException(e);
    } finally {
        //don't care about the connection any more
        removeConnectionListener();
    }
}

From source file:com.andyadc.menagerie.locks.ZkCondition.java

License:Apache License

@Override
public long awaitNanos(long nanosTimeout) throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    if (!distributedLock.hasLock())
        throw new IllegalMonitorStateException("await was called without owning the associated lock");
    try {/*ww w.  ja v a  2  s . c o  m*/
        //release the associated zkLock
        distributedLock.unlock();

        //put a signal node onto zooKeeper, then wait for it to be deleted
        ZooKeeper zooKeeper = zkSessionManager.getZooKeeper();
        String conditionName = zooKeeper.create(baseNode + "/" + conditionPrefix + conditionDelimiter,
                emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL);

        long timeLeft = nanosTimeout;
        while (true) {
            if (Thread.interrupted()) {
                zooKeeper.delete(conditionName, -1);
                throw new InterruptedException();
            }
            if (checkTimeout(zooKeeper, conditionName, timeLeft))
                return timeLeft;

            long start = System.nanoTime();
            localLock.lock();
            try {
                long endTime = System.nanoTime();
                timeLeft -= (endTime - start);
                if (checkTimeout(zooKeeper, conditionName, timeLeft))
                    return timeLeft;
                else if (zooKeeper.exists(conditionName, signalWatcher) == null) {
                    //we have been signalled, so relock and then return
                    return timeLeft;
                } else {
                    timeLeft = condition.awaitNanos(timeLeft);
                }
            } finally {
                localLock.unlock();
            }
        }
    } catch (KeeperException e) {
        throw new RuntimeException(e);
    } finally {
        distributedLock.lock();
    }
}

From source file:com.andyadc.menagerie.locks.ZkCondition.java

License:Apache License

/**
 * Chooses a party which is waiting on this lock, and signals it.
 * <p>//from   ww w  . j a v  a  2s  .  c  o m
 * Note:This implementation does NOT check the interrupted status of the current thread, as it prioritizes that
 * a signal ALWAYS be sent, if there is a party waiting for that signal.
 *
 * @see #signal() in java.util.concurrent.locks.Condition
 */
@Override
public void signal() {
    if (!distributedLock.hasLock())
        throw new IllegalMonitorStateException("Signal is attempted without first owning the signalling lock");

    ZooKeeper zooKeeper = zkSessionManager.getZooKeeper();
    try {
        List<String> conditionsToSignal = ZkUtils.filterByPrefix(zooKeeper.getChildren(baseNode, false),
                conditionPrefix);
        if (conditionsToSignal.size() <= 0)
            return; //no parties to signal

        //delete the lowest numbered waiting party
        ZkUtils.sortBySequence(conditionsToSignal, conditionDelimiter);
        zooKeeper.delete(baseNode + "/" + conditionsToSignal.get(0), -1);

    } catch (KeeperException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.andyadc.menagerie.locks.ZkCondition.java

License:Apache License

@Override
public void signalAll() {
    if (!distributedLock.hasLock())
        throw new IllegalMonitorStateException("Signal is attempted without first owning the signalling lock");

    ZooKeeper zooKeeper = zkSessionManager.getZooKeeper();
    try {/*  w w w.j a v a 2 s  .c  o m*/
        List<String> conditionsToSignal = ZkUtils.filterByPrefix(zooKeeper.getChildren(baseNode, false),
                conditionPrefix);
        if (conditionsToSignal.size() <= 0)
            return; //no parties to signal

        //notify all waiting conditions in sequence
        ZkUtils.sortBySequence(conditionsToSignal, conditionDelimiter);

        for (String condition : conditionsToSignal) {
            zooKeeper.delete(baseNode + "/" + condition, -1);
        }
    } catch (KeeperException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.andyadc.menagerie.locks.ZkCondition.java

License:Apache License

private boolean checkTimeout(ZooKeeper zooKeeper, String nodeName, long timeLeft)
        throws InterruptedException, KeeperException {
    if (timeLeft <= 0) {
        //timed out
        zooKeeper.delete(nodeName, -1);
        return true;
    }//w  w  w . j a  v  a  2 s  .com
    return false;
}

From source file:com.andyadc.menagerie.ZkUtils.java

License:Apache License

/**
 * Deletes an element from ZooKeeper safely.
 * <p>//w  w  w.ja  va  2  s . com
 * If the element has already been deleted from ZooKeeper, then a NoNode Exception is normally thrown by ZooKeeper.
 * This method suppresses those NoNode exceptions .
 *
 * @param zk           the ZooKeeper client to use
 * @param nodeToDelete the node to delete
 * @param version      the version of that node to remove
 * @return true if the node was deleted
 * @throws KeeperException      if some issue with the ZooKeeper server occurs
 * @throws InterruptedException if some communication error happens
 *                              between the ZooKeeper client and the ZooKeeper service
 */
public static boolean safeDelete(ZooKeeper zk, String nodeToDelete, int version)
        throws KeeperException, InterruptedException {
    try {
        zk.delete(nodeToDelete, version);
        return true;
    } catch (KeeperException ke) {
        //if the node has already been deleted, don't worry about it
        if (ke.code() != KeeperException.Code.NONODE)
            throw ke;
        else
            return false;
    }
}

From source file:com.asuraiv.coordination.menu.MainMenu.java

License:Open Source License

/**
 * ? ? ()./*from  w  ww  .j a  v  a 2  s  . c o  m*/
 */
private void doDeleteTasks() {
    try {

        ZooKeeper zk = new ZooKeeper("10.113.182.195:2181", 15000, this);

        System.out.println();
        System.out.println("###    ###");

        List<String> tasks = zk.getChildren("/tasks", false, null);

        if (CollectionUtils.isEmpty(tasks)) {
            System.out.println("[WARNNING]  ?? ? .");
            return;
        }

        for (String task : tasks) {
            zk.delete("/tasks/" + task, -1);
            System.out.println(task + " ? ");
        }

        zk.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeeperException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.bigdata.service.jini.master.TaskMaster.java

License:Open Source License

/**
 * Sets up the {@link JobState} in zookeeper, including the assignment of
 * service {@link UUID}s to each client. {@link #jobState} will be replaced
 * with the {@link JobState} read from zookeeper if a pre-existing job is
 * found in zookeeper./*from  ww  w  . j a  v a  2s  .  c o  m*/
 * 
 * @return The global lock for the master running the job.
 * 
 * @throws KeeperException
 * @throws InterruptedException
 * @throws TimeoutException
 */
protected ZLock setupJob() throws KeeperException, InterruptedException, TimeoutException {

    final ZooKeeper zookeeper = fed.getZookeeperAccessor().getZookeeper();

    try {
        // ensure znode exists.
        zookeeper.create(fed.getZooConfig().zroot + "/" + BigdataZooDefs.JOBS, new byte[0],
                fed.getZooConfig().acl, CreateMode.PERSISTENT);
    } catch (NodeExistsException ex) {
        // ignore.
    }

    final String jobClassZPath = jobState.getJobClassZPath(fed);

    try {
        // ensure znode exists.
        zookeeper.create(jobClassZPath, new byte[0], fed.getZooConfig().acl, CreateMode.PERSISTENT);
    } catch (NodeExistsException ex) {
        // ignore.
    }

    /*
     * Use a global lock to protect the job.
     * 
     * Note: We just created parent of this lock node (or at any rate,
     * ensured that it exists).
     */
    final ZLock zlock = ZLockImpl.getLock(zookeeper, jobClassZPath + "/" + "locknode_" + jobState.jobName,
            fed.getZooConfig().acl);

    zlock.lock();
    try {

        final String jobZPath = jobState.getJobZPath(fed);

        if (jobState.deleteJob && zookeeper.exists(jobZPath, false/* watch */) != null) {

            /*
             * Delete old job.
             */

            log.warn("Deleting old job: " + jobZPath);

            ZooHelper.destroyZNodes(fed.getZookeeperAccessor().getZookeeper(), jobZPath, 0/* depth */);

            // detach the performance counters for the old job.
            detachPerformanceCounters();

        }

        try {

            // create znode that is the root for the job.
            zookeeper.create(jobZPath, SerializerUtil.serialize(jobState), fed.getZooConfig().acl,
                    CreateMode.PERSISTENT);

            if (log.isInfoEnabled())
                log.info("New job: " + jobState);

            try {

                /*
                 * Assign clients to services.
                 */
                final DiscoveredServices discoveredServices = new DiscoverServicesWithPreconditionsTask()
                        .call();

                jobState.clientServiceMap.assignClientsToServices(discoveredServices.clientServiceItems);

                jobState.aggregatorServiceMap
                        .assignClientsToServices(discoveredServices.aggregatorServiceItems);

                // write those assignments into zookeeper.
                zookeeper.setData(jobZPath, SerializerUtil.serialize(jobState), -1/* version */);

                if (log.isInfoEnabled())
                    log.info("Wrote client assignments into zookeeper.");

            } catch (Throwable t) {

                /*
                 * Since we created the jobState znode, delete the jobState
                 * while we are still holding the zlock.
                 */
                try {
                    zookeeper.delete(jobZPath, -1/* version */);
                } catch (Throwable t2) {
                    log.error(t2);
                }

                throw new RuntimeException(t);

            }

        } catch (NodeExistsException ex) {

            /*
             * Resuming a job already in progress and/or providing backup
             * clients for a job that is currently running.
             * 
             * Note: We use the client to data service UUID assignments read
             * from the znode data which are part of the jobState
             * 
             * @todo stable assignments are only required when clients will
             * read or write local data. This is not the common case and
             * should be a declarative configuration option.
             */

            jobState = (S) SerializerUtil.deserialize(zookeeper.getData(jobZPath, false, new Stat()));

            jobState.clientServiceMap.resolveServiceUUIDs(fed);

            jobState.aggregatorServiceMap.resolveServiceUUIDs(fed);

            jobState.resumedJob = true;

            log.warn("Pre-existing job: " + jobZPath);

        }

    } catch (KeeperException t) {

        zlock.unlock();

        throw t;

    } catch (InterruptedException t) {

        zlock.unlock();

        throw t;

    } catch (Throwable t) {

        zlock.unlock();

        throw new RuntimeException(t);

    }

    return zlock;

}

From source file:com.bigdata.zookeeper.AbstractZooTestCase.java

License:Open Source License

/**
 * Recursive delete of znodes.//  ww  w .j av a2  s .co  m
 * 
 * @param zpath
 * 
 * @throws KeeperException
 * @throws InterruptedException
 */
protected void destroyZNodes(final ZooKeeper zookeeper, final String zpath)
        throws KeeperException, InterruptedException {

    // System.err.println("enter : " + zpath);

    final List<String> children = zookeeper.getChildren(zpath, false);

    for (String child : children) {

        destroyZNodes(zookeeper, zpath + "/" + child);

    }

    if (log.isInfoEnabled())
        log.info("delete: " + zpath);

    zookeeper.delete(zpath, -1/* version */);

}