List of usage examples for org.apache.zookeeper Watcher Watcher
Watcher
From source file:org.labs.qbit.election.leader.ElectionClient.java
License:Open Source License
public ElectionClient() throws IOException { int numberOfThreads = 20; executorService = Executors.newFixedThreadPool(numberOfThreads); logger.debug("Executor Service is being initialized with FixedThreadPool [NumberOfThread: {}]", numberOfThreads);//from w w w . j a va 2 s . co m zooKeeper = new ZooKeeper("localhost:2181", 2000, new Watcher() { @Override public void process(WatchedEvent event) { logger.debug("An event occurred on root path"); } }); }
From source file:org.lilyproject.hadooptestfw.CleanupUtil.java
License:Apache License
public void cleanZooKeeper() throws Exception { int sessionTimeout = 10000; ZooKeeper zk = new ZooKeeper(zkConnectString, sessionTimeout, new Watcher() { @Override/*from www. jav a2 s . co m*/ public void process(WatchedEvent event) { if (event.getState() == Watcher.Event.KeeperState.Disconnected) { System.err.println("ZooKeeper Disconnected."); } else if (event.getState() == Event.KeeperState.Expired) { System.err.println("ZooKeeper session expired."); } } }); long waitUntil = System.currentTimeMillis() + sessionTimeout; while (zk.getState() != CONNECTED && waitUntil > System.currentTimeMillis()) { try { Thread.sleep(20); } catch (InterruptedException e) { break; } } if (zk.getState() != CONNECTED) { throw new RuntimeException("Failed to connect to ZK within " + sessionTimeout + "ms."); } if (zk.exists("/lily", false) != null) { System.out.println("----------------- Clearing '/lily' node in ZooKeeper -------------------"); List<String> paths = new ArrayList<String>(); collectChildren("/lily", zk, paths); paths.add("/lily"); for (String path : paths) { zk.delete(path, -1, null, null); } long startWait = System.currentTimeMillis(); while (zk.exists("/lily", null) != null) { Thread.sleep(5); if (System.currentTimeMillis() - startWait > 120000) { throw new RuntimeException("State was not cleared in ZK within the expected timeout"); } } System.out.println("Deleted " + paths.size() + " paths from ZooKeeper"); System.out.println("------------------------------------------------------------------------"); } zk.close(); }
From source file:org.lilyproject.testfw.HBaseProxy.java
License:Apache License
public void cleanZooKeeper() throws Exception { int sessionTimeout = 10000; ZooKeeper zk = new ZooKeeper(getZkConnectString(), sessionTimeout, new Watcher() { public void process(WatchedEvent event) { if (event.getState() == Watcher.Event.KeeperState.Disconnected) { System.err.println("ZooKeeper Disconnected."); } else if (event.getState() == Event.KeeperState.Expired) { System.err.println("ZooKeeper session expired."); }//from ww w . jav a 2 s . com } }); long waitUntil = System.currentTimeMillis() + sessionTimeout; while (zk.getState() != CONNECTED && waitUntil > System.currentTimeMillis()) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } if (zk.getState() != CONNECTED) { throw new RuntimeException("Failed to connect to ZK within " + sessionTimeout + "ms."); } if (zk.exists("/lily", false) != null) { System.out.println("----------------- Clearing '/lily' node in ZooKeeper -------------------"); deleteChildren("/lily", zk); zk.delete("/lily", -1); System.out.println("------------------------------------------------------------------------"); } zk.close(); }
From source file:org.lilyproject.util.zookeeper.ZooKeeperMXBean.java
License:Apache License
/** * Invalidates our ZooKeeper's session. Meant for testing purposes. * * <p>Note that you can also close connections and sessions through the JMX beans provided by the ZooKeeper * server(s), which I find often more practical. *//* w w w . java 2 s.c o m*/ public void invalidateSession() throws IOException, InterruptedException { // The below is the standard way to invalidate a session from the client. // See also http://github.com/phunt/zkexamples/blob/master/src/test_session_expiration/TestSessionExpiration.java // where it is mentioned that this could also lead to a session moved exception. Watcher watcher = new Watcher() { public void process(WatchedEvent event) { } }; ZooKeeper zk2 = new ZooKeeper(connectString, sessionTimeout, watcher, zk.getSessionId(), zk.getSessionPasswd()); long waitUntil = System.currentTimeMillis() + sessionTimeout; while (zk2.getState() != CONNECTED && waitUntil > System.currentTimeMillis()) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } if (zk2.getState() != CONNECTED) { throw new IOException("Failed to make a connection with ZooKeeper within the timeout " + sessionTimeout + ", connect string: " + connectString); } else { zk2.close(); } }
From source file:org.loggo.client.ZooSocketAppender.java
License:Apache License
private void connect() { if (socket != null) { return;// w w w . j ava 2s. co m } if (connector != null) { return; } if (zookeeper == null) { return; } try { LogLog.debug("Reading registered loggers from " + zookeepers); List<String> children = zookeeper.getChildren("/", new Watcher() { @Override public void process(WatchedEvent event) { LogLog.debug("Detected a change in loggers, reconnecting"); close(); connect(); } }); if (children.isEmpty()) { LogLog.debug("No loggers found"); return; } LogLog.debug("Found " + children.size() + " loggers registered at " + zookeepers); Random random = new Random(); int choice = random.nextInt(children.size()); String path = "/" + children.get(choice); byte[] data = zookeeper.getData(path, false, null); String address = new String(data, UTF_8); LogLog.debug("Selected logger at " + address); String parts[] = address.split(":", 2); if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) { LogLog.debug("Unable to parse address " + address + " found at " + path); } int port = Integer.decode(parts[1]); connector = new Connector(parts[0], port); connector.start(); } catch (KeeperException | InterruptedException e) { LogLog.debug("Exception reading from zookeeper: " + e, e); } catch (Exception ex) { LogLog.debug("Error " + ex.toString(), ex); } }
From source file:org.loggo.client.ZooUDPAppender.java
License:Apache License
private void reconfigure() { List<String> children; try {/*from ww w . j ava2 s. c om*/ children = zookeeper.getChildren("/", new Watcher() { @Override public void process(WatchedEvent arg0) { reconfigure(); } }); if (children.isEmpty()) { LogLog.debug("Zookeeper list of loggers is empty"); return; } Random random = new Random(); int choice = random.nextInt(children.size()); byte[] data = zookeeper.getData("/" + children.get(choice), false, null); String dataString = new String(data, UTF_8); String parts[] = dataString.split(":"); address = InetAddress.getByName(parts[0]); port = Integer.decode(parts[1]); connect(address, port); } catch (UnknownHostException | KeeperException | InterruptedException e) { LogLog.debug("Exception " + e); } }
From source file:org.loggo.server.Server.java
License:Apache License
private void registerInZookeeper(Configuration config) throws IOException, KeeperException, InterruptedException { String zookeepers = config.getString("zookeepers"); if (zookeepers != null) { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zookeeper = new ZooKeeper(zookeepers, 30 * 1000, new Watcher() { @Override/* w w w . j av a2 s . c o m*/ public void process(WatchedEvent event) { latch.countDown(); } }); try { latch.await(); try { zookeeper.create("/udp", new byte[] {}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException ex) { // expected } String host = config.getString("host"); int port = config.getInt("udp.port"); zookeeper.create("/udp/logger-", (host + ":" + port).getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); try { zookeeper.create("/tcp", new byte[] {}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException ex) { // expected } port = config.getInt("tcp.port"); zookeeper.create("/tcp/logger-", (host + ":" + port).getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); } finally { zookeeper.close(); } } }
From source file:org.loggo.server.SimpleServerIT.java
License:Apache License
@BeforeClass public static void setup() throws Exception { File baseDir = new File(System.getProperty("user.dir") + "/target/" + SimpleServerIT.class.getName()); FileUtils.deleteDirectory(baseDir);/*from ww w. ja va2s . c o m*/ assertTrue(baseDir.mkdirs() || baseDir.isDirectory()); String passwd = "secret"; cluster = new MiniAccumuloClusterImpl(new MiniAccumuloConfigImpl(baseDir, passwd)); cluster.start(); conn = cluster.getConnector("root", new PasswordToken(passwd)); File kafkaConfig = new File(baseDir, "kafkaConfig"); File kafkaLogs = new File(baseDir, "kafkaLogs"); loggerPort = PortUtils.getRandomFreePort(); String configString = KAFKA_CONFIG; configString = configString.replace("%ZOOKEEPER%", cluster.getZooKeepers()); configString = configString.replace("%PORT%", "" + loggerPort); configString = configString.replace("%LOGS%", kafkaLogs.toString()); FileUtils.write(kafkaConfig, configString); kafka = cluster.exec(Kafka.class, kafkaConfig.toString()); final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zookeeper = new ZooKeeper(cluster.getZooKeepers(), 10 * 1000, new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("Got a zookeeper event: " + event); latch.countDown(); } }); latch.await(); LOG.info("Assuming zookeeper connected"); assertEquals(ZooKeeper.States.CONNECTED, zookeeper.getState()); zookeeper.create("/loggers", new byte[] {}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zookeeper.close(); ServerConfiguration config = new ServerConfiguration(); kafkaPort = PortUtils.getRandomFreePort(); configString = LOGGER_CONFIG; configString = configString.replace("%ZOOKEEPER%", cluster.getZooKeepers()); configString = configString.replace("%INSTANCE%", cluster.getInstanceName()); configString = configString.replace("%PORT%", "" + kafkaPort); System.out.println(configString); config.load(new StringReader(configString)); server = new Server(); server.initialize(config); // start a log service threadPool.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { return server.run(); } }); // wait for it to start sleepUninterruptibly(1, TimeUnit.SECONDS); }
From source file:org.midonet.midolman.state.ZkDumper.java
License:Apache License
private static void setupZKConnection(final String host, final int port) throws Exception { int magic = 3000; // FIXME System.out.println("Connecting to ZooKeeper at " + host + ":" + port); zk = new ZooKeeper(host + ":" + port, magic, new Watcher() { @Override/*w w w . ja va 2 s . com*/ public synchronized void process(WatchedEvent event) { if (event.getState() == KeeperState.Disconnected) { System.err.println("Disconnected from ZooKeeper"); System.exit(-1); } else if (event.getState() == KeeperState.SyncConnected) { System.out.println("Connected to ZooKeeper at " + host + ":" + port); available.release(); } else if (event.getState() == KeeperState.Expired) { System.err.println("Session expired"); System.exit(-1); } } }); System.out.println("In progress to ZooKeeper at " + host + ":" + port); available.acquire(); }
From source file:org.midonet.midolman.state.ZkLock.java
License:Apache License
public void lock(final Callback<Void, StateAccessException> callback) { try {/* ww w . j a va 2 s . co m*/ final String path = zk.addEphemeralSequential(lockPath, null); int seq = ZkUtil.getSequenceNumberFromPath(path); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { acquire(path, callback); } }; String prev; do { Set<String> waiters = zk.getChildren(lockPath, null); prev = ZkUtil.getNextLowerSequenceNumberPath(waiters, seq); if (prev == null) { acquire(path, callback); return; } } while (!zk.exists(lockPath + "/" + prev, watcher)); } catch (StateAccessException e) { log.error("Got exception when trying to acquire {}", lockPath, e); callback.onError(e); } }