Example usage for org.apache.zookeeper WatchedEvent getType

List of usage examples for org.apache.zookeeper WatchedEvent getType

Introduction

In this page you can find the example usage for org.apache.zookeeper WatchedEvent getType.

Prototype

public EventType getType() 

Source Link

Usage

From source file:org.apache.bookkeeper.client.TestBookieWatcher.java

License:Apache License

private void expireZooKeeperSession(ZooKeeper zk, int timeout)
        throws IOException, InterruptedException, KeeperException {
    final CountDownLatch latch = new CountDownLatch(1);
    ZooKeeper newZk = new ZooKeeper(zkUtil.getZooKeeperConnectString(), timeout, new Watcher() {

        @Override/* ww  w.  ja v a 2s . c  om*/
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                latch.countDown();
            }
        }

    }, zk.getSessionId(), zk.getSessionPasswd());
    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }
    newZk.close();
}

From source file:org.apache.bookkeeper.client.TestBookieWatcher.java

License:Apache License

@Test(timeout = 10000)
public void testBookieWatcherDieWhenSessionExpired() throws Exception {
    final int timeout = 2000;
    final CountDownLatch connectLatch = new CountDownLatch(1);
    ZooKeeper zk = new ZooKeeper(zkUtil.getZooKeeperConnectString(), timeout, new Watcher() {
        @Override/*from www. ja v  a  2  s. com*/
        public void process(WatchedEvent watchedEvent) {
            if (EventType.None == watchedEvent.getType()
                    && KeeperState.SyncConnected == watchedEvent.getState()) {
                connectLatch.countDown();
            }
        }
    });
    connectLatch.await();
    try {
        runBookieWatcherWhenSessionExpired(zk, timeout, false);
    } finally {
        zk.close();
    }
}

From source file:org.apache.bookkeeper.discover.ZKRegistrationManager.java

License:Apache License

/**
 * Check existence of <i>regPath</i> and wait it expired if possible.
 *
 * @param regPath reg node path.//from w w w.  j  ava2s .co  m
 * @return true if regPath exists, otherwise return false
 * @throws IOException if can't create reg path
 */
protected boolean checkRegNodeAndWaitExpired(String regPath) throws IOException {
    final CountDownLatch prevNodeLatch = new CountDownLatch(1);
    Watcher zkPrevRegNodewatcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            // Check for prev znode deletion. Connection expiration is
            // not handling, since bookie has logic to shutdown.
            if (EventType.NodeDeleted == event.getType()) {
                prevNodeLatch.countDown();
            }
        }
    };
    try {
        Stat stat = zk.exists(regPath, zkPrevRegNodewatcher);
        if (null != stat) {
            // if the ephemeral owner isn't current zookeeper client
            // wait for it to be expired.
            if (stat.getEphemeralOwner() != zk.getSessionId()) {
                log.info("Previous bookie registration znode: {} exists, so waiting zk sessiontimeout:"
                        + " {} ms for znode deletion", regPath, zkTimeoutMs);
                // waiting for the previous bookie reg znode deletion
                if (!prevNodeLatch.await(zkTimeoutMs, TimeUnit.MILLISECONDS)) {
                    throw new NodeExistsException(regPath);
                } else {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    } catch (KeeperException ke) {
        log.error("ZK exception checking and wait ephemeral znode {} expired : ", regPath, ke);
        throw new IOException("ZK exception checking and wait ephemeral znode " + regPath + " expired", ke);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        log.error("Interrupted checking and wait ephemeral znode {} expired : ", regPath, ie);
        throw new IOException("Interrupted checking and wait ephemeral znode " + regPath + " expired", ie);
    }
}

From source file:org.apache.bookkeeper.meta.AbstractZkLedgerManager.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    LOG.info("Received watched event {} from zookeeper based ledger manager.", event);
    if (Event.EventType.None == event.getType()) {
        /** TODO: BOOKKEEPER-537 to handle expire events.
        if (Event.KeeperState.Expired == event.getState()) {
        LOG.info("ZooKeeper client expired on ledger manager.");
        Set<Long> keySet = new HashSet<Long>(listeners.keySet());
        for (Long lid : keySet) {/*from w  ww.  ja va 2  s. c  om*/
            scheduler.submit(new ReadLedgerMetadataTask(lid));
            LOG.info("Re-read ledger metadata for {} after zookeeper session expired.", lid);
        }
        }
        **/
        return;
    }
    String path = event.getPath();
    if (null == path) {
        return;
    }
    final long ledgerId;
    try {
        ledgerId = getLedgerId(event.getPath());
    } catch (IOException ioe) {
        LOG.info("Received invalid ledger path {} : ", event.getPath(), ioe);
        return;
    }
    switch (event.getType()) {
    case NodeDeleted:
        Set<LedgerMetadataListener> listenerSet = listeners.get(ledgerId);
        if (null != listenerSet) {
            synchronized (listenerSet) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Removed ledger metadata listeners on ledger {} : {}", ledgerId, listenerSet);
                }
                for (LedgerMetadataListener l : listenerSet) {
                    l.onChanged(ledgerId, null);
                }
                listeners.remove(ledgerId, listenerSet);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No ledger metadata listeners to remove from ledger {} after it's deleted.",
                        ledgerId);
            }
        }
        break;
    case NodeDataChanged:
        new ReadLedgerMetadataTask(ledgerId).run();
        break;
    default:
        LOG.debug("Received event {} on {}.", event.getType(), event.getPath());
        break;
    }
}

From source file:org.apache.bookkeeper.meta.ZkLedgerUnderreplicationManager.java

License:Apache License

@Override
public long getLedgerToRereplicate() throws ReplicationException.UnavailableException {
    LOG.debug("getLedgerToRereplicate()");
    try {//from ww w  .  jav  a 2  s  . co  m
        while (true) {
            waitIfLedgerReplicationDisabled();
            final CountDownLatch changedLatch = new CountDownLatch(1);
            Watcher w = new Watcher() {
                public void process(WatchedEvent e) {
                    if (e.getType() == Watcher.Event.EventType.NodeChildrenChanged
                            || e.getType() == Watcher.Event.EventType.NodeDeleted
                            || e.getType() == Watcher.Event.EventType.NodeCreated
                            || e.getState() == Watcher.Event.KeeperState.Expired
                            || e.getState() == Watcher.Event.KeeperState.Disconnected) {
                        changedLatch.countDown();
                    }
                }
            };
            long ledger = getLedgerToRereplicateFromHierarchy(urLedgerPath, 0, w);
            if (ledger != -1) {
                return ledger;
            }
            // nothing found, wait for a watcher to trigger
            changedLatch.await();
        }
    } catch (KeeperException ke) {
        throw new ReplicationException.UnavailableException("Error contacting zookeeper", ke);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new ReplicationException.UnavailableException("Interrupted while connecting zookeeper", ie);
    }
}

From source file:org.apache.bookkeeper.meta.ZkLedgerUnderreplicationManager.java

License:Apache License

@Override
public void notifyLedgerReplicationEnabled(final GenericCallback<Void> cb)
        throws ReplicationException.UnavailableException {
    LOG.debug("notifyLedgerReplicationEnabled()");
    Watcher w = new Watcher() {
        public void process(WatchedEvent e) {
            if (e.getType() == Watcher.Event.EventType.NodeDeleted) {
                cb.operationComplete(0, null);
            }/*from w ww  . j a va 2  s. com*/
        }
    };
    try {
        if (null == zkc.exists(basePath + '/' + BookKeeperConstants.DISABLE_NODE, w)) {
            cb.operationComplete(0, null);
            return;
        }
    } catch (KeeperException ke) {
        LOG.error("Error while checking the state of " + "ledger re-replication", ke);
        throw new ReplicationException.UnavailableException("Error contacting zookeeper", ke);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new ReplicationException.UnavailableException("Interrupted while contacting zookeeper", ie);
    }
}

From source file:org.apache.bookkeeper.replication.BookieAutoRecoveryTest.java

License:Apache License

private Stat watchUrLedgerNode(final String znode, final CountDownLatch latch)
        throws KeeperException, InterruptedException {
    return zkc.exists(znode, new Watcher() {
        @Override/*from  ww w . j  a v a2s . c om*/
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.NodeDeleted) {
                LOG.info("Recieved Ledger rereplication completion event :" + event.getType());
                latch.countDown();
            }
            if (event.getType() == EventType.NodeCreated) {
                LOG.info("Recieved urLedger publishing event :" + event.getType());
                latch.countDown();
            }
        }
    });
}

From source file:org.apache.bookkeeper.replication.TestLedgerUnderreplicationManager.java

License:Apache License

/**
 * Test enabling the ledger re-replication. After enableLedegerReplication,
 * should continue getLedgerToRereplicate() task
 *///from   w w w. j a v a 2s .c  o m
@Test(timeout = 20000)
public void testEnableLedgerReplication() throws Exception {
    isLedgerReplicationDisabled = true;
    final LedgerUnderreplicationManager replicaMgr = lmf1.newLedgerUnderreplicationManager();

    // simulate few urLedgers before disabling
    final Long ledgerA = 0xfeadeefdacL;
    final String missingReplica = "localhost:3181";
    try {
        replicaMgr.markLedgerUnderreplicated(ledgerA, missingReplica);
    } catch (UnavailableException e) {
        LOG.debug("Unexpected exception while marking urLedger", e);
        fail("Unexpected exception while marking urLedger" + e.getMessage());
    }

    // disabling replication
    replicaMgr.disableLedgerReplication();
    LOG.debug("Disabled Ledeger Replication");

    String znodeA = getUrLedgerZnode(ledgerA);
    final CountDownLatch znodeLatch = new CountDownLatch(2);
    String urledgerA = StringUtils.substringAfterLast(znodeA, "/");
    String urLockLedgerA = basePath + "/locks/" + urledgerA;
    zkc1.exists(urLockLedgerA, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.NodeCreated) {
                znodeLatch.countDown();
                LOG.debug("Recieved node creation event for the zNodePath:" + event.getPath());
            }

        }
    });
    // getLedgerToRereplicate is waiting until enable rereplication
    Thread thread1 = new Thread() {
        @Override
        public void run() {
            try {
                Long lA = replicaMgr.getLedgerToRereplicate();
                assertEquals("Should be the ledger I just marked", lA, ledgerA);
                isLedgerReplicationDisabled = false;
                znodeLatch.countDown();
            } catch (UnavailableException e) {
                LOG.debug("Unexpected exception while marking urLedger", e);
                isLedgerReplicationDisabled = false;
            }
        }
    };
    thread1.start();

    try {
        assertFalse("shouldn't complete", znodeLatch.await(1, TimeUnit.SECONDS));
        assertTrue("Ledger replication is not disabled!", isLedgerReplicationDisabled);
        assertEquals("Failed to disable ledger replication!", 2, znodeLatch.getCount());

        replicaMgr.enableLedgerReplication();
        znodeLatch.await(5, TimeUnit.SECONDS);
        LOG.debug("Enabled Ledeger Replication");
        assertTrue("Ledger replication is not disabled!", !isLedgerReplicationDisabled);
        assertEquals("Failed to disable ledger replication!", 0, znodeLatch.getCount());
    } finally {
        thread1.interrupt();
    }
}

From source file:org.apache.bookkeeper.test.CloseTest.java

License:Apache License

/**
 * Watcher method. //from   w ww.j av a 2  s. c  om
 */
synchronized public void process(WatchedEvent event) {
    LOG.info("Process: " + event.getType() + " " + event.getPath());
}

From source file:org.apache.bookkeeper.tools.BookKeeperTools.java

License:Apache License

/**
 * Constructor that takes in a ZooKeeper servers connect string so we know
 * how to connect to ZooKeeper to retrieve information about the BookKeeper
 * cluster. We need this before we can do any type of admin operations on
 * the BookKeeper cluster./*w w w . j a  va2 s.c  o  m*/
 * 
 * @param zkServers
 *            Comma separated list of hostname:port pairs for the ZooKeeper
 *            servers cluster.
 * @throws IOException
 *             Throws this exception if there is an error instantiating the
 *             ZooKeeper client.
 * @throws InterruptedException
 *             Throws this exception if there is an error instantiating the
 *             BookKeeper client.
 * @throws KeeperException
 *             Throws this exception if there is an error instantiating the
 *             BookKeeper client.
 */
public BookKeeperTools(String zkServers) throws IOException, InterruptedException, KeeperException {
    // Create the ZooKeeper client instance
    zk = new ZooKeeper(zkServers, 10000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Process: " + event.getType() + " " + event.getPath());
            }
        }
    });
    // Create the BookKeeper client instance
    bkc = new BookKeeper(zk);
}