Example usage for org.apache.zookeeper Watcher Watcher

List of usage examples for org.apache.zookeeper Watcher Watcher

Introduction

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

Prototype

Watcher

Source Link

Usage

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

License:Apache License

@Test
public void testConstructionNotConnectedExplicitZk() throws Exception {
    ClientConfiguration conf = new ClientConfiguration().setZkServers(zkUtil.getZooKeeperConnectString())
            .setZkTimeout(20000);/*w  ww. j  a  v a  2 s . c o  m*/

    CountDownLatch l = new CountDownLatch(1);
    zkUtil.sleepServer(5, l);
    l.await();

    ZooKeeper zk = new ZooKeeper(zkUtil.getZooKeeperConnectString(), 10000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
        }
    });
    assertFalse("ZK shouldn't have connected yet", zk.getState().isConnected());
    try {
        BookKeeper bkc = new BookKeeper(conf, zk);
        fail("Shouldn't be able to construct with unconnected zk");
    } catch (KeeperException.ConnectionLossException cle) {
        // correct behaviour
    }
}

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/* w w w.  ja  v a 2 s  .  c o m*/
        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 w w w  .  ja v  a  2s  .  c o m
        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 a v a 2 s.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.ZkLedgerUnderreplicationManager.java

License:Apache License

@Override
public long pollLedgerToRereplicate() throws ReplicationException.UnavailableException {
    LOG.debug("pollLedgerToRereplicate()");
    try {/*from  www . j av a 2s .  com*/
        Watcher w = new Watcher() {
            public void process(WatchedEvent e) { // do nothing
            }
        };
        return getLedgerToRereplicateFromHierarchy(urLedgerPath, 0, w);
    } 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 long getLedgerToRereplicate() throws ReplicationException.UnavailableException {
    LOG.debug("getLedgerToRereplicate()");
    try {/*www  .  j a  v a2  s.  com*/
        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);
            }/*ww  w.  j  a v a 2s  .  c om*/
        }
    };
    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.AutoRecoveryMain.java

License:Apache License

public AutoRecoveryMain(ServerConfiguration conf, StatsLogger statsLogger) throws IOException,
        InterruptedException, KeeperException, UnavailableException, CompatibilityException {
    this.conf = conf;
    Set<Watcher> watchers = new HashSet<Watcher>();
    // TODO: better session handling for auto recovery daemon  https://issues.apache.org/jira/browse/BOOKKEEPER-594
    //       since {@link org.apache.bookkeeper.meta.ZkLedgerUnderreplicationManager}
    //       use Watcher, need to ensure the logic works correctly after recreating
    //       a new zookeeper client when session expired.
    //       for now just shutdown it.
    watchers.add(new Watcher() {
        @Override//from w w w .  j  ava  2s  .  c  om
        public void process(WatchedEvent event) {
            // Check for expired connection.
            if (event.getState().equals(Watcher.Event.KeeperState.Expired)) {
                LOG.error("ZK client connection to the ZK server has expired!");
                shutdown(ExitCode.ZK_EXPIRED);
            }
        }
    });
    zk = ZooKeeperClient.newBuilder().connectString(conf.getZkServers()).sessionTimeoutMs(conf.getZkTimeout())
            .watchers(watchers).build();
    auditorElector = new AuditorElector(Bookie.getBookieAddress(conf).toString(), conf, zk,
            statsLogger.scope(AUDITOR_SCOPE));
    replicationWorker = new ReplicationWorker(zk, conf, Bookie.getBookieAddress(conf),
            statsLogger.scope(REPLICATION_WORKER_SCOPE));
    deathWatcher = new AutoRecoveryDeathWatcher(this);
}

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 w  ww  .  jav a 2  s . 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 ava2  s .  c  om*/
@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();
    }
}