List of usage examples for org.apache.zookeeper ZooKeeper register
public synchronized void register(Watcher watcher)
From source file:com.nearinfinity.blur.manager.indexserver.BlurServerShutDown.java
License:Apache License
public void register(final BlurShutdown shutdown, ZooKeeper zooKeeper) { this.shutdown = shutdown; this.zooKeeper = zooKeeper; zooKeeper.register(new Watcher() { @Override//from w ww.j a va 2s .com public void process(WatchedEvent event) { KeeperState state = event.getState(); if (state == KeeperState.Expired) { LOG.fatal("Zookeeper session has [" + state + "] server process shutting down."); shutdown.shutdown(); } } }); }
From source file:com.yahoo.pulsar.zookeeper.GlobalZooKeeperCache.java
License:Apache License
public void start() throws IOException { CompletableFuture<ZooKeeper> zkFuture = zlClientFactory.create(globalZkConnect, SessionType.AllowReadOnly, zkSessionTimeoutMillis);/* w w w .ja va2s . c o m*/ // Initial session creation with global ZK must work try { ZooKeeper newSession = zkFuture.get(10, TimeUnit.SECONDS); // Register self as a watcher to receive notification when session expires and trigger a new session to be // created newSession.register(this); zkSession.set(newSession); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOG.error("Failed to establish global zookeeper session: {}", e.getMessage(), e); throw new IOException(e); } }
From source file:org.apache.bookkeeper.benchmark.BenchReadThroughputLatency.java
License:Apache License
@SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("ledger", true, "Ledger to read. If empty, read all ledgers which come available. " + " Cannot be used with -listen"); options.addOption("listen", true, "Listen for creation of <arg> ledgers, and read each one fully"); options.addOption("password", true, "Password used to access ledgers (default 'benchPasswd')"); options.addOption("zookeeper", true, "Zookeeper ensemble, default \"localhost:2181\""); options.addOption("sockettimeout", true, "Socket timeout for bookkeeper client. In seconds. Default 5"); options.addOption("help", false, "This message"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { usage(options);//from w w w .j a va 2 s . c om System.exit(-1); } final String servers = cmd.getOptionValue("zookeeper", "localhost:2181"); final byte[] passwd = cmd.getOptionValue("password", "benchPasswd").getBytes(UTF_8); final int sockTimeout = Integer.parseInt(cmd.getOptionValue("sockettimeout", "5")); if (cmd.hasOption("ledger") && cmd.hasOption("listen")) { LOG.error("Cannot used -ledger and -listen together"); usage(options); System.exit(-1); } final AtomicInteger ledger = new AtomicInteger(0); final AtomicInteger numLedgers = new AtomicInteger(0); if (cmd.hasOption("ledger")) { ledger.set(Integer.parseInt(cmd.getOptionValue("ledger"))); } else if (cmd.hasOption("listen")) { numLedgers.set(Integer.parseInt(cmd.getOptionValue("listen"))); } else { LOG.error("You must use -ledger or -listen"); usage(options); System.exit(-1); } final CountDownLatch shutdownLatch = new CountDownLatch(1); final CountDownLatch connectedLatch = new CountDownLatch(1); final String nodepath = String.format("/ledgers/L%010d", ledger.get()); final ClientConfiguration conf = new ClientConfiguration(); conf.setReadTimeout(sockTimeout).setZkServers(servers); final ZooKeeper zk = new ZooKeeper(servers, 3000, new Watcher() { public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected && event.getType() == Event.EventType.None) { connectedLatch.countDown(); } } }); final Set<String> processedLedgers = new HashSet<String>(); try { zk.register(new Watcher() { public void process(WatchedEvent event) { try { if (event.getState() == Event.KeeperState.SyncConnected && event.getType() == Event.EventType.None) { connectedLatch.countDown(); } else if (event.getType() == Event.EventType.NodeCreated && event.getPath().equals(nodepath)) { readLedger(conf, ledger.get(), passwd); shutdownLatch.countDown(); } else if (event.getType() == Event.EventType.NodeChildrenChanged) { if (numLedgers.get() < 0) { return; } List<String> children = zk.getChildren("/ledgers", true); List<String> ledgers = new ArrayList<String>(); for (String child : children) { if (LEDGER_PATTERN.matcher(child).find()) { ledgers.add(child); } } for (String ledger : ledgers) { synchronized (processedLedgers) { if (processedLedgers.contains(ledger)) { continue; } final Matcher m = LEDGER_PATTERN.matcher(ledger); if (m.find()) { int ledgersLeft = numLedgers.decrementAndGet(); final Long ledgerId = Long.valueOf(m.group(1)); processedLedgers.add(ledger); Thread t = new Thread() { public void run() { readLedger(conf, ledgerId, passwd); } }; t.start(); if (ledgersLeft <= 0) { shutdownLatch.countDown(); } } else { LOG.error("Cant file ledger id in {}", ledger); } } } } else { LOG.warn("Unknown event {}", event); } } catch (Exception e) { LOG.error("Exception in watcher", e); } } }); connectedLatch.await(); if (ledger.get() != 0) { if (zk.exists(nodepath, true) != null) { readLedger(conf, ledger.get(), passwd); shutdownLatch.countDown(); } else { LOG.info("Watching for creation of" + nodepath); } } else { zk.getChildren("/ledgers", true); } shutdownLatch.await(); LOG.info("Shutting down"); } finally { zk.close(); } }
From source file:org.apache.curator.HandleHolder.java
License:Apache License
private void internalClose() throws Exception { try {//from w w w. j av a2 s . com ZooKeeper zooKeeper = (helper != null) ? helper.getZooKeeper() : null; if (zooKeeper != null) { Watcher dummyWatcher = new Watcher() { @Override public void process(WatchedEvent event) { } }; zooKeeper.register(dummyWatcher); // clear the default watcher so that no new events get processed by mistake zooKeeper.close(); } } catch (InterruptedException dummy) { Thread.currentThread().interrupt(); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java
License:Apache License
@VisibleForTesting @Private/*from w ww . j a va 2 s. c o m*/ @Unstable protected synchronized ZooKeeper getNewZooKeeper() throws IOException, InterruptedException { ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, null); zk.register(new ForwardingWatcher()); return zk; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java
License:Apache License
@VisibleForTesting @Private//from w ww . j a v a 2 s .c o m @Unstable protected synchronized ZooKeeper getNewZooKeeper() throws IOException, InterruptedException { ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, null); zk.register(new ForwardingWatcher(zk)); return zk; }
From source file:org.apache.hedwig.server.topics.ZkHubServerManager.java
License:Apache License
public ZkHubServerManager(ServerConfiguration conf, ZooKeeper zk, HedwigSocketAddress addr, TopicManager tm) { this.conf = conf; this.zk = zk; this.addr = addr; this.tm = tm; // znode path to store all available hub servers this.hubNodesPath = this.conf.getZkHostsPrefix(new StringBuilder()).toString(); // the node's ephemeral node path this.ephemeralNodePath = getHubZkNodePath(addr); this.executor = Executors.newSingleThreadScheduledExecutor(); // register available hub servers list watcher zk.register(new ZkHubsWatcher()); // Start the rebalancer here. new RebalanceRunnable(conf.getRebalanceTolerance(), conf.getRebalanceMaxShed(), conf.getRebalanceInterval()) .start();// w w w .j a v a 2 s .c o m }
From source file:org.lable.oss.uniqueid.zookeeper.connection.ZooKeeperConnection.java
License:Apache License
/** * Connect to the ZooKeeper quorum, or timeout if it is unreachable. * * @throws IOException Thrown when connecting to the ZooKeeper quorum fails. *///w w w . j av a 2 s.com private static void connect() throws IOException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zookeeper; // Connect to the quorum and wait for the successful connection callback.; zookeeper = new ZooKeeper(quorumAddresses, (int) SECONDS.toMillis(10), new Watcher() { @Override public void process(WatchedEvent watchedEvent) { if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { // Signal that the Zookeeper connection is established. latch.countDown(); } } }); boolean successfullyConnected = false; try { successfullyConnected = latch.await(11, SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (!successfullyConnected) { throw new IOException(String.format("Connection to ZooKeeper quorum timed out after %d seconds.", CONNECTION_TIMEOUT)); } zookeeper.register(new ConnectionWatcher()); INSTANCE.zookeeper = zookeeper; }