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:com.nokia.dempsy.mpcluster.zookeeper.TestZookeeperClusterResilience.java

License:Apache License

@Test
public void testRecoverWithIOException() throws Throwable {
    // now lets startup the server.
    ZookeeperTestServer server = null;/*w  w w .  j  a va 2s .  com*/
    ZookeeperSession<String, String> session = null;
    try {
        server = new ZookeeperTestServer();
        server.start();

        session = new ZookeeperSession<String, String>("127.0.0.1:" + port, 5000) {
            @Override
            protected ZooKeeper makeZookeeperInstance(String connectString, int sessionTimeout)
                    throws IOException {
                if (forceIOException.get()) {
                    forceIOExceptionLatch.countDown();
                    throw new IOException("Fake IO Problem.");
                }
                return super.makeZookeeperInstance(connectString, sessionTimeout);
            }
        };

        MpCluster<String, String> cluster = session
                .getCluster(new ClusterId(appname, "testRecoverWithIOException"));
        TestWatcher callback = new TestWatcher();
        cluster.addWatcher(callback);

        assertNotNull(cluster);

        // now see if the cluster works.
        cluster.getActiveSlots();

        // cause a problem with the server running lets sever the connection
        // according to the zookeeper faq we can force a session expired to occur by closing the session from another client.
        // see: http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4
        ZooKeeper origZk = session.zkref.get();
        long sessionid = origZk.getSessionId();
        ZooKeeper killer = new ZooKeeper("127.0.0.1:" + port, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent arg0) {
            }
        }, sessionid, null);

        // force the ioexception to happen
        forceIOException.set(true);

        killer.close(); // tricks the server into expiring the other session

        // just stop the damn server
        server.shutdown();

        // now in the background it should be retrying but hosed.
        assertTrue(forceIOExceptionLatch.await(baseTimeoutMillis * 3, TimeUnit.MILLISECONDS));

        // There is no longer a callback on a disconnect....only a callback when the reconnect is successful         
        //         // wait for the callback
        //         for (long endTime = System.currentTimeMillis() + baseTimeoutMillis; endTime > System.currentTimeMillis() && !callback.called.get();)
        //            Thread.sleep(1);
        //         assertTrue(callback.called.get());

        // TODO: do I really meed this sleep?
        Thread.sleep(1000);

        // now the getActiveSlots call should fail since i'm preventing the recovery by throwing IOExceptions
        boolean gotCorrectError = false;
        for (long endTime = System.currentTimeMillis() + baseTimeoutMillis; endTime > System.currentTimeMillis()
                && !gotCorrectError;) {
            Thread.sleep(1);
            try {
                cluster.join("yo");
            } catch (MpClusterException e) {
                gotCorrectError = true;
            }
        }
        assertTrue(gotCorrectError);

        callback.called.set(false); // reset the callbacker ...

        // now we should allow the code to proceed.
        forceIOException.set(false);

        // we might want the server running.
        server = new ZookeeperTestServer();
        server.start();

        // wait for the callback
        for (long endTime = System.currentTimeMillis() + baseTimeoutMillis; endTime > System.currentTimeMillis()
                && !callback.called.get();)
            Thread.sleep(1);
        assertTrue(callback.called.get());

        // this should eventually recover.
        gotCorrectError = true;
        for (long endTime = System.currentTimeMillis() + baseTimeoutMillis; endTime > System.currentTimeMillis()
                && gotCorrectError;) {
            Thread.sleep(1);
            try {
                cluster.getActiveSlots();
                gotCorrectError = false;
            } catch (MpClusterException e) {
            }
        }

        cluster.getActiveSlots();

        // And join should work
        gotCorrectError = true;
        for (long endTime = System.currentTimeMillis() + baseTimeoutMillis; endTime > System.currentTimeMillis()
                && gotCorrectError;) {
            Thread.sleep(1);
            try {
                cluster.join("join-1");
                gotCorrectError = false;
            } catch (MpClusterException e) {
            }
        }

        assertFalse(gotCorrectError);
    } finally {
        if (server != null)
            server.shutdown();

        if (session != null)
            session.stop();
    }
}

From source file:com.palantir.atlasdb.transaction.service.ZooKeeperMetadataStorageService.java

License:Open Source License

private void init() {
    try {// w w w . j a v  a2 s .  c  om
        zooKeeper = new ZooKeeper(servers, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                // do nothing
            }
        });
    } catch (IOException e) {
        throw Throwables.throwUncheckedException(e);
    }
}

From source file:com.proofpoint.zookeeper.crossprocess.CrossProcessLockImp.java

License:Apache License

/**
 * Allocate a lock for the given path. The mutex locks on other ZKLocks with the same
 * path in this JVM or other JVMs connected to the same Zookeeper cluster
 *
 * @param zookeeper the zookeeper client
 * @param name lock path/*from  w  w  w.jav a 2  s  .c om*/
 */
public CrossProcessLockImp(ZooKeeper zookeeper, String name) {
    this.zookeeper = zookeeper;
    basePath = name;
    this.path = makePath(name);
    watcher = new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            notifyFromWatcher();
        }
    };

    lockPath = null;
}

From source file:com.rapleaf.hank.ZkTestCase.java

License:Apache License

@Override
protected void setUp() throws Exception {
    super.setUp();
    Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN);

    setupZkServer();/*from   w w  w  . ja  va  2  s  . co  m*/

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    createNodeRecursively(zkRoot);
}

From source file:com.renren.zookeeper.accessor.test.PublishTest.java

License:Open Source License

@BeforeClass
public static void init() throws IOException, KeeperException {
    if (zookeeperBackgroundServer == null) {
        zookeeperBackgroundServer = new ZookeeperBackgroundServer();
        Thread zkBackgroundServer = new Thread(zookeeperBackgroundServer);
        zkBackgroundServer.setDaemon(true);
        zkBackgroundServer.start();/*w w  w.  j a v a2 s . co  m*/
    }
    config = new ZkConfig();
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    zooKeeper = new ZooKeeper(config.getHost(), config.getSessionTime(), new Watcher() {

        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                countDownLatch.countDown();
            } else if (event.getType() == EventType.None && event.getState() == KeeperState.Disconnected) {
                System.err.println("The connection between zookeeper server and localhost has down.");
            }
        }
    });
    try {
        countDownLatch.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException e1) {
        System.err.println("Can't connect zookeeper server, please check 2181 port and config file.");
        e1.printStackTrace();
        throw new IOException("Can't connect zookeeper server.");
    }
    try {
        accessor = Accessor.getInstance(config);
        recursiveDelete('/' + PREFIX_STRING);
        try {
            zooKeeper.delete('/' + config.getRoot(), -1);
        } catch (KeeperException.NoNodeException e1) {
            // node not exist, ignore.
        }
        zooKeeper.create('/' + config.getRoot(), null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        recursiveCreate('/' + PREFIX_STRING);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.sharksharding.resources.conn.ZookeeperConnectionManager.java

License:Apache License

/**
 * zookeeper/*  w  ww.ja v a  2  s  .  c  om*/
 * 
 * @author JohnGao
 */
private void connection() {
    try {
        zk_client = new ZooKeeper(zk_address, zk_session_timeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                final KeeperState STATE = event.getState();
                switch (STATE) {
                case SyncConnected:
                    countDownLatch.countDown();
                    logger.info("connection zookeeper success");
                    break;
                case Disconnected:
                    logger.warn("zookeeper connection is disconnected");
                    break;
                case Expired:
                    logger.error("zookeeper session expired");
                    break;
                case AuthFailed:
                    logger.error("authentication failure");
                default:
                    break;
                }
            }
        });
        countDownLatch.await();
        /* ?? */
        registerNode.register(zk_client, nodePath);
    } catch (IOException | InterruptedException e) {
        throw new ConnectionException(e.toString());
    }
}

From source file:com.sharksharding.util.sequence.zookeeper.ZookeeperConnectionManager.java

License:Apache License

/**
 * zookeeper/*from   ww w  .  ja  va  2s  .c  o m*/
 * 
 * @author gaoxianglong
 * 
 * @throws ConnectionException
 * 
 * @return void
 */
private static void connection() throws ConnectionException {
    try {
        zk_client = new ZooKeeper(zk_address, zk_session_timeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                final KeeperState STATE = event.getState();
                switch (STATE) {
                case SyncConnected:
                    countDownLatch.countDown();
                    logger.info("connection zookeeper success");
                    break;
                case Disconnected:
                    logger.warn("zookeeper connection is disconnected");
                    break;
                case Expired:
                    logger.error("zookeeper session expired");
                    break;
                case AuthFailed:
                    logger.error("authentication failure");
                default:
                    break;
                }
            }
        });
        countDownLatch.await();
        setZk_client(zk_client);
    } catch (IOException | InterruptedException e) {
        throw new ConnectionException(e.toString());
    }
}

From source file:com.smartitengineering.cms.spi.lock.impl.distributed.AppTest.java

License:Open Source License

@Test
public void testInitialization() throws Exception {

    ZooKeeper zooKeeper = new ZooKeeper(connectString, CONNECTION_TIMEOUT, new Watcher() {

        public void process(WatchedEvent event) {
        }/*from  ww w  . j av  a  2 s .co m*/
    });
    Stat stat = zooKeeper.exists(ROOT_NODE, false);
    Assert.assertNull(stat);
    final LocalLockRegistrarImpl localLockRegistrarImpl = new LocalLockRegistrarImpl();
    localLockRegistrarImpl.initTimeoutChecking();
    ZooKeeperLockHandler handler = new ZooKeeperLockHandler(connectString, ROOT_NODE, "node1",
            CONNECTION_TIMEOUT, localLockRegistrarImpl);
    stat = zooKeeper.exists(ROOT_NODE, false);
    Assert.assertNotNull(stat);
}

From source file:com.smartitengineering.cms.spi.lock.impl.distributed.ZKLock.java

License:Open Source License

protected boolean tryRemoteLock(String lockId, final long availableMillisForRemoteLock)
        throws IllegalStateException, InterruptedException {
    final LocalLockRegistrar registrar = config.getRegistrar();
    final ZooKeeper keeper = config.getZooKeeper();
    final String node = getNode();
    if (logger.isDebugEnabled()) {
        logger.debug("Attained local lock " + lockId);
    }// ww w.j a  va 2 s. com
    try {
        if (StringUtils.isNotBlank(lockId)) {
            keeper.create(node, org.apache.commons.codec.binary.StringUtils.getBytesUtf8(config.getNodeId()),
                    Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            keeper.exists(node, this);
            localLockId = lockId;
            return true;
        } else {
            return false;
        }
    } catch (KeeperException ke) {
        if (ke.code() == KeeperException.Code.NODEEXISTS) {
            logger.debug("Lock alrady exists!");
            if (availableMillisForRemoteLock > 0) {
                synchronized (ZKLock.this) {
                    try {
                        keeper.exists(node, new Watcher() {

                            public void process(WatchedEvent event) {
                                if (event.getType().equals(Event.EventType.NodeDeleted)) {
                                    synchronized (ZKLock.this) {
                                        ZKLock.this.notifyAll();
                                    }
                                }
                            }
                        });
                    } catch (Exception ex) {
                        logger.error("Could not attach watcher", ex);
                    }
                    final long remoteStart = System.currentTimeMillis();
                    ZKLock.this.wait(availableMillisForRemoteLock);
                    return tryRemoteLock(lockId,
                            availableMillisForRemoteLock - (System.currentTimeMillis() - remoteStart));
                }
            } else {
                registrar.unlock(key, lockId);
                return false;
            }
        } else {
            logger.error(ke.getMessage(), ke);
            throw new IllegalStateException(ke);
        }
    } catch (Exception ex) {
        registrar.unlock(key, lockId);
        logger.error(ex.getMessage(), ex);
        throw new IllegalStateException(ex);
    }
}

From source file:com.sonian.elasticsearch.zookeeper.client.ZooKeeperClientService.java

License:Apache License

@Override
protected void doStart() throws ElasticsearchException {
    try {/*from  w w w  . j  a va 2 s .  co  m*/
        final Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                switch (event.getState()) {
                case Expired:
                    resetSession();
                    break;
                case SyncConnected:
                    notifySessionConnected();
                    break;
                case Disconnected:
                    notifySessionDisconnected();
                    break;
                }
            }
        };
        zooKeeper = zooKeeperFactory.newZooKeeper(watcher);
        createPersistentNode(environment.rootNodePath());
        createPersistentNode(environment.clustersNodePath());
    } catch (InterruptedException e) {
        throw new ZooKeeperClientException("Cannot start ZooKeeper client", e);
    }
}