Example usage for org.apache.zookeeper CreateMode EPHEMERAL_SEQUENTIAL

List of usage examples for org.apache.zookeeper CreateMode EPHEMERAL_SEQUENTIAL

Introduction

In this page you can find the example usage for org.apache.zookeeper CreateMode EPHEMERAL_SEQUENTIAL.

Prototype

CreateMode EPHEMERAL_SEQUENTIAL

To view the source code for org.apache.zookeeper CreateMode EPHEMERAL_SEQUENTIAL.

Click Source Link

Document

The znode will be deleted upon the client's disconnect, and its name will be appended with a monotonically increasing number.

Usage

From source file:blazingcache.zookeeper.ZKClusterManager.java

License:Apache License

/**
 *
 * @throws Exception in case of issue on starting the cluster manager
 *//*www  .  jav a 2  s.com*/
public void start() throws Exception {
    try {
        if (this.zk.exists(basePath, false) == null) {
            LOGGER.log(Level.SEVERE, "creating base path " + basePath);
            try {
                this.zk.create(basePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } catch (KeeperException anyError) {
                throw new Exception("Could not init Zookeeper space at path " + basePath, anyError);
            }
        }
        if (this.zk.exists(discoverypath, false) == null) {
            LOGGER.log(Level.SEVERE, "creating discoverypath path " + discoverypath);
            try {
                this.zk.create(discoverypath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } catch (KeeperException anyError) {
                throw new Exception("Could not init Zookeeper space at path " + discoverypath, anyError);
            }
        }
        String newPath = zk.create(discoverypath + "/brokers", localhostdata, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        LOGGER.log(Level.SEVERE, "my own discoverypath path is " + newPath);

    } catch (KeeperException error) {
        throw new Exception("Could not init Zookeeper space at path " + basePath, error);
    }
}

From source file:blazingcache.zookeeper.ZKClusterManager.java

License:Apache License

/**
 * register back brokers ephemeral nodes after session recovery.
 *
 * @throws Exception in case node creation ends up with issues
 *///w ww. ja  v  a2 s  .  co  m
private void registerZKNodes() throws Exception {
    final String completeDiscoveryPath = discoverypath + "/brokers";
    String newPath = zk.create(completeDiscoveryPath, localhostdata, ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.EPHEMERAL_SEQUENTIAL);
    LOGGER.log(Level.SEVERE, "my own discoverypath path is " + newPath);
}

From source file:cn.lhfei.zookeeper.ch01.Client.java

License:Apache License

String queueCommand(String command) throws Exception {
    while (true) {
        try {//w w  w .ja  va 2  s . c o  m
            String name = zk.create(CURRENT_NODE, command.getBytes(), Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL_SEQUENTIAL);
            return name;
        } catch (NodeExistsException e) {
            throw new Exception(" already appears to be running");
        } catch (ConnectionLossException e) {
        }

    }
}

From source file:co.paralleluniverse.galaxy.zookeeper.ZooKeeperCluster.java

License:Open Source License

@Override
protected void init() throws Exception {
    super.init();
    client = CuratorFrameworkFactory.builder().namespace(zkNamespace).connectString(zkConnectString)
            .sessionTimeoutMs(sessionTimeoutMs).connectionTimeoutMs(connectionTimeoutMs)
            .retryPolicy(retryPolicy).defaultData(new byte[0]).build();
    client.start();//from  ww  w  .  j av  a2s .  c o  m

    try {
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(ROOT + "/node_names");
    } catch (KeeperException.NodeExistsException e) {
    }

    myNodeName = child(client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
            .forPath(ROOT + "/node_names" + "/node-"));
    LOG.info("Node name is {}, id is {}", myNodeName, myId);
    setName(myNodeName);

    initRefIdCounter();

    final ZooKeeperDistributedTree tree = new ZooKeeperDistributedTree(client);
    setControlTree(tree);

    super.init(); // super.init() must be called after setControlTree()
}

From source file:co.paralleluniverse.galaxy.zookeeper.ZooKeeperDistributedTree.java

License:Open Source License

@Override
public void createEphemeralOrdered(String node) {
    try {//from   w  w w  .java 2  s.co  m
        LOG.info("Creating ephemeral ordered node {}", node);
        if (exists(node)) {
            LOG.info("Node {} already exists ({})", node, possiblyWithSequence(node));
            return;
        }
        String nameWithSequence = client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(node + ':');
        LOG.info("Created node {}", nameWithSequence);
        putOrdered(node, nameWithSequence);
    } catch (Exception ex) {
        LOG.error("Node " + node + " creation has failed!", ex);
        throw Throwables.propagate(ex);
    }
}

From source file:com.alibaba.otter.shared.arbitrate.impl.zookeeper.lock.DistributedLock.java

License:Apache License

/**
 * lock??watch????lock?// www .  j a v  a  2s . co  m
 */
private Boolean acquireLock(final BooleanMutex mutex) {
    try {
        do {
            if (id == null) {// ?lock
                long sessionId = getSessionId();
                String prefix = "x-" + sessionId + "-";
                // 
                String path = zookeeper.create(root + "/" + prefix, data, CreateMode.EPHEMERAL_SEQUENTIAL);
                int index = path.lastIndexOf("/");
                id = StringUtils.substring(path, index + 1);
                idName = new LockNode(id);
            }

            if (id != null) {
                List<String> names = zookeeper.getChildren(root);
                if (names.isEmpty()) {
                    logger.warn("lock lost with scene:empty list, id[] and node[]", id, idName);
                    unlock();// ??
                } else {
                    // ?
                    SortedSet<LockNode> sortedNames = new TreeSet<LockNode>();
                    for (String name : names) {
                        sortedNames.add(new LockNode(name));
                    }

                    if (sortedNames.contains(idName) == false) {
                        logger.warn("lock lost with scene:not contains ,id[] and node[]", id, idName);
                        unlock();// ??
                        continue;
                    }

                    // ?ownerId
                    ownerId = sortedNames.first().getName();
                    if (mutex != null && isOwner()) {
                        mutex.set(true);// ?
                        return true;
                    } else if (mutex == null) {
                        return isOwner();
                    }

                    SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName);
                    if (!lessThanMe.isEmpty()) {
                        // ?
                        LockNode lastChildName = lessThanMe.last();
                        lastChildId = lastChildName.getName();
                        // watcher?
                        IZkConnection connection = zookeeper.getConnection();
                        // zkclient?zk?lock??watcher?zk?
                        ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper();
                        Stat stat = orginZk.exists(root + "/" + lastChildId, new AsyncWatcher() {

                            public void asyncProcess(WatchedEvent event) {
                                if (!mutex.state()) { // ?????lock
                                    acquireLock(mutex);
                                } else {
                                    logger.warn("locked successful.");
                                }
                            }

                        });

                        if (stat == null) {
                            acquireLock(mutex);// ????watcher?
                        }
                    } else {
                        if (isOwner()) {
                            mutex.set(true);
                        } else {
                            logger.warn("lock lost with scene:no less ,id[] and node[]", id, idName);
                            unlock();// ?idownerId??
                        }
                    }
                }
            }
        } while (id == null);
    } catch (KeeperException e) {
        exception = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (InterruptedException e) {
        interrupt = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (Throwable e) {
        other = e;
        if (mutex != null) {
            mutex.set(true);
        }
    }

    if (isOwner() && mutex != null) {
        mutex.set(true);
    }
    return Boolean.FALSE;
}

From source file:com.alibaba.otter.shared.common.utils.zookeeper.ZkClientx.java

License:Apache License

/**
 * Create an ephemeral, sequential node.
 * /*from   w  w w.j  a v a 2  s .c o m*/
 * @param path
 * @param data
 * @return created path
 * @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 createEphemeralSequential(final String path, final Object data)
        throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
    return create(path, data, CreateMode.EPHEMERAL_SEQUENTIAL);
}

From source file:com.andyadc.menagerie.latches.ZkCountDownLatch.java

License:Apache License

/**
 * Creates a new CountDownLatch on the specified latchNode, or joins a CountDownLatch which has been
 * previously created by another node/thread on the same latchNode.
 * <p>//  w  ww  .j  a  va  2s . c o  m
 * When this constructor returns, the Latch is guaranteed to be in a cluster- and thread-safe state which
 * is ready to be used.
 * <p>
 * This constructor creates a CountDownLatch where the caller can choose between node-fault tolerance and algorithmic
 * certainty. If {@code tolerateFailures} is set to true, then once a party has counted down against this latch, it
 * will remain counted down, even if that party subsequently fails. To require that all parties remain alive until
 * the latch has been reached, set {@code tolerateFailures} to false.
 *
 * @param total            the number of elements which must countDown before threads may proceed.
 * @param latchNode        the node to execute the latch under
 * @param zkSessionManager the ZkSessionManager to use
 * @param privileges       the privileges for this latch
 * @param tolerateFailures set to {@code true} to ensure that nodes can progress once all parties have reported once;
 *                         set to false to require <i>all</i> parties to remain connected until the Latch has been filled.
 * @throws RuntimeException wrapping:
 *                          <ul>
 *                          <li> {@link KeeperException} if the ZooKeeper Server has trouble with the requests
 *                          <li> {@link InterruptedException} if the ZooKeeper client has trouble communicating with the ZooKeeper service
 *                          </ul>
 */
public ZkCountDownLatch(long total, String latchNode, ZkSessionManager zkSessionManager, List<ACL> privileges,
        boolean tolerateFailures) {
    super(total, latchNode, zkSessionManager, privileges);
    this.countDownMode = tolerateFailures ? CreateMode.PERSISTENT_SEQUENTIAL : CreateMode.EPHEMERAL_SEQUENTIAL;
    ensureState();
}

From source file:com.andyadc.menagerie.latches.ZkCyclicBarrier.java

License:Apache License

/**
 * Creates a new CyclicBarrier, or joins a CyclicBarrier which has been previously created by another party
 * on the same latchNode.//from  w ww. j  a  va 2 s .  c o m
 * <p>
 * This constructor checks to ensure that the barrier is in a good state before returning. If the latchNode was the
 * site of a previously broken barrier, then the Barrier is reset as if the {@link #reset()} method was called.
 * <p>
 * When this constructor returns, the latch is guaranteed to be in a clear, unbroken state and is ready to be
 * used.
 * <p>
 * This constructor creates a CyclicBarrier where the caller can choose between node-fault tolerance and algorithmic
 * certainty. If {@code tolerateFailures} is set to true, then once a party has entered this latch, it
 * will remain entered (with respect to the other parties), even if that party subsequently fails.
 * To require that all parties remain alive until the latch has been reached, set {@code tolerateFailures} to false.
 *
 * @param zkSessionManager the ZkSessionManager to use
 * @param barrierNode      the node the execute the barrier under
 * @param privileges       the privileges for this latch
 * @param tolerateFailures set to {@code true} to allow the Barrier to proceed even if some parties fail after
 *                         entering the barrier. Set to false to require all parties to remain alive until the barrier is
 *                         completed.
 * @param size             the number of elements which must enter the barrier before threads may proceed.
 */
public ZkCyclicBarrier(long size, ZkSessionManager zkSessionManager, String barrierNode, List<ACL> privileges,
        boolean tolerateFailures) {
    super(size, barrierNode, zkSessionManager, privileges);

    this.barrierMode = tolerateFailures ? CreateMode.PERSISTENT_SEQUENTIAL : CreateMode.EPHEMERAL_SEQUENTIAL;
    ensureNodeExists();
    //        try {
    //            checkReset();
    //            System.out.printf("%s: Created new CyclicBarrier%n",Thread.currentThread().getName());
    //        } catch (KeeperException e) {
    //            throw new RuntimeException(e);
    //        } catch (InterruptedException e) {
    //            throw new RuntimeException(e);
    //        }
}

From source file:com.andyadc.menagerie.latches.ZkCyclicBarrier.java

License:Apache License

/**
 * Waits until all parties have been invoked on this barrier, or until the maximum time has been reached.
 * <p>/*from w w w  . j av  a 2s.c  o  m*/
 * If the current thread is not the last to arrive, then it is disabled for thread-scheduling purposes and lies
 * dormant until one of the following conditions are realized:
 * <ol>
 * <li>The Last party arrives
 * <li>Some other thread interrupts the current thread
 * <li>Some other Thread interrupts one of the other waiting parties
 * <li>Some other party times out while waiting for the barrier
 * <li>Some other party invokes {@link #reset()} on this barrier
 * <li>This barrier is intolerant of party failures, and some other party prematurely leaves the barrier
 * due to an external system event such as a network failure
 * <li>This thread reaches its time limit (set by {@code timeout}).
 * </ol>
 * <p>
 * If the current thread:
 * <ul>
 * <li> has its interrupted status set on entry to this method; or
 * <li> is interrupted while waiting
 * </ul>
 * <p>
 * Then the Barrier is broken for all other parties, and an {@link InterruptedException}
 * is thrown on this thread, clearing the current interrupted status.
 * <p>
 * This Barrier is considered <i>broken</i> if one of the following conditions apply:
 * <ol>
 * <li>Another party times out while waiting for the barrier
 * <li>Another party invoked {@link #reset()} on this barrier
 * <li>Another party prematurely leaves the barrier due to an external system event such as a network failure,
 * and this barrier is set to be intolerant of party failures
 * <li>Another party received notification of a Thread Interruption
 * </ol>
 * <p>
 * If any of these situations occur, a {@link BrokenBarrierException} is thrown.
 * <p>
 * If the maximum time is reached, and the barrier has not been completed, the barrier will be broken for
 * all other parties, and a {@link TimeoutException} will be thrown on this thread.
 * <p>
 * <p>Note that, unlike {@link java.util.concurrent.CyclicBarrier} in the standarad JDK, this method
 * does <em>not</em> return a count of this thread's position in the barrier. This is because it is essentially
 * impossible to do so accurately.
 *
 * @param timeout the maximum amount of time to wait for the barrier to complete
 * @param unit    the TimeUnit to use
 * @throws InterruptedException   if the local thread is interrupted, or if there is a communication error
 *                                with ZooKeeper
 * @throws BrokenBarrierException if another party breaks the barrier, or another party calls reset while
 *                                waiting for the Barrier to complete
 * @throws TimeoutException       if the maximum wait time is exceeded before the Barrier can be
 *                                completed.
 */
public void await(long timeout, TimeUnit unit)
        throws InterruptedException, BrokenBarrierException, TimeoutException {
    long timeLeftNanos = unit.toNanos(timeout);
    //add my node to the collection

    String myNode = null;
    try {
        myNode = zkSessionManager.getZooKeeper().create(getBarrierBasePath(), emptyNode, privileges,
                CreateMode.EPHEMERAL_SEQUENTIAL);

        while (timeLeftNanos > 0) {
            long start = System.nanoTime();
            boolean acquired = localLock.tryLock(timeLeftNanos, TimeUnit.NANOSECONDS);
            long end = System.nanoTime();
            timeLeftNanos -= (end - start);
            if (!acquired || timeLeftNanos < 0)
                throw new TimeoutException();
            try {
                if (isCleared()) {
                    //the Barrier has been cleared, so we are done
                    return;
                } else {
                    ZooKeeper zk = zkSessionManager.getZooKeeper();
                    List<String> barrierChildren = ZkUtils
                            .filterByPrefix(zk.getChildren(baseNode, signalWatcher), barrierPrefix);
                    int currentChildren = barrierChildren.size();
                    if (currentChildren >= total) {
                        //we've finished, so let's clear and return
                        ZkUtils.safeCreate(zk, getClearedPath(), emptyNode, privileges, CreateMode.PERSISTENT);
                        return;
                    } else if (localCount.get() > barrierChildren.size())
                        throw new BrokenBarrierException();
                    else {
                        localCount.set(barrierChildren.size());
                        /*
                        we know that the barrierChildren's size is at least as large as the local count,
                        but it isn't large enough to finish yet.
                        so let's wait until we receive word that something has changed
                        */
                        timeLeftNanos = condition.awaitNanos(timeLeftNanos);
                    }
                }
            } finally {
                localLock.unlock();
            }
        }
        throw new TimeoutException();
    } catch (KeeperException e) {
        throw new RuntimeException(e);
    } finally {
        //delete myNode
        if (myNode != null) {
            try {
                ZkUtils.safeDelete(zkSessionManager.getZooKeeper(), myNode, -1);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            }
        }
    }
}