List of usage examples for org.apache.zookeeper WatchedEvent getState
public KeeperState getState()
From source file:com.andyadc.menagerie.ZkSessionPoller.java
License:Apache License
public static void main(String... args) throws Exception { Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.INFO); rootLogger.addAppender(new ConsoleAppender(new SimpleLayout())); final ZooKeeper zk = new ZooKeeper("172.16.84.129:2181", 2000, new Watcher() { @Override/*ww w .ja va 2s . c o m*/ public void process(WatchedEvent event) { System.out.printf("state=%s\ttype=%s%n", event.getState(), event.getType()); } }); final CountDownLatch latch = new CountDownLatch(1); ZkSessionPoller poller = new ZkSessionPoller(zk, 200, new ConnectionListenerSkeleton() { @Override public void expired() { System.err.println("Session Expired, shutting down."); try { zk.close(); } catch (InterruptedException e) { throw new RuntimeException(e); } latch.countDown(); } }); poller.startPolling(); latch.await(); poller.stopPolling(); }
From source file:com.anteam.demo.zookeeper.DataMonitor.java
License:Apache License
@SuppressWarnings("deprecation") public void process(WatchedEvent event) { System.out.println("----------------------------------------"); System.out.println("event:" + event); String path = event.getPath(); System.out.println("DataMonitor.process.path:" + path); if (event.getType() == Event.EventType.None) { // We are are being told that the state of the // connection has changed switch (event.getState()) { case SyncConnected: // In this particular example we don't need to do anything // here - watches are automatically re-registered with // server and any watches triggered while the client was // disconnected will be delivered (in order of course) break; case Expired: // It's all over dead = true;/*from ww w. jav a 2 s. c o m*/ listener.closing(KeeperException.Code.SessionExpired); break; default: break; } } else { if (path != null && path.equals(znode)) { // Something has changed on the node, let's find out zk.exists(znode, true, this, null); } } if (chainedWatcher != null) { chainedWatcher.process(event); } }
From source file:com.api6.zkclient.watcher.ZKWatcher.java
License:Apache License
/** * ?/*from w ww . j ava 2 s. c o m*/ * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent) */ @Override public void process(WatchedEvent event) { LOG.debug("ZooKeeper event is arrived [" + event + " ]..."); EventType eventType = event.getType(); //? boolean stateChanged = event.getPath() == null; // boolean znodeChanged = event.getPath() != null; //??? boolean nodeChanged = eventType == EventType.NodeDataChanged || eventType == EventType.NodeDeleted || eventType == EventType.NodeCreated; //??????????? boolean childChanged = eventType == EventType.NodeDeleted || eventType == EventType.NodeCreated || eventType == EventType.NodeChildrenChanged; client.acquireEventLock(); try { if (client.getShutdownTrigger()) { LOG.debug("client will shutdown,ignore the event [" + eventType + " | " + event.getPath() + "]"); return; } if (stateChanged) {//ZooKeeper??? process.processStateChanged(event); } if (nodeChanged) {//?????? process.processNodeChanged(event); } if (childChanged) {//?????????? process.processChildChanged(event); } } finally { if (stateChanged) { client.getEventLock().getStateChangedCondition().signalAll(); // ????watch. // ???????? // ???? if (event.getState() == KeeperState.Expired) { client.getEventLock().getNodeEventCondition().signalAll(); client.getEventLock().getNodeOrChildChangedCondition().signalAll(); // ???? process.processAllNodeAndChildListeners(event); } } if (znodeChanged) { client.getEventLock().getNodeEventCondition().signalAll(); } if (nodeChanged || childChanged) { client.getEventLock().getNodeOrChildChangedCondition().signalAll(); } client.releaseEventLock(); } }
From source file:com.api6.zkclient.watcher.ZKWatcherProcess.java
License:Apache License
public void processStateChanged(WatchedEvent event) { final KeeperState keeperState = event.getState(); LOG.info("ZooKeeper state is changed [" + keeperState + "] ."); //?ZooKeeper? client.setCurrentState(keeperState); if (client.getShutdownTrigger()) { return;/*from w w w. j a v a2s . c o m*/ } //?? Set<ZKStateListener> listeners = client.getStateListenerSet(); //??? for (final ZKStateListener stateListener : listeners) { eventThreadPool.submit(new ZKEvent("State changed to " + keeperState + " sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleStateChanged(keeperState); } }); } //???? if (event.getState() == KeeperState.Expired) { try { //?? client.reconnect(); //?? for (final ZKStateListener stateListener : listeners) { ZKEvent zkEvent = new ZKEvent("New session event sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleNewSession(); } }; eventThreadPool.submit(zkEvent); } } catch (final Exception e) { LOG.info("Unable to re-establish connection. Notifying consumer of the following exception: ", e); //???? for (final ZKStateListener stateListener : listeners) { eventThreadPool .submit(new ZKEvent("Session establishment error[" + e + "] sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleSessionError(e); } }); } } } }
From source file:com.att.research.music.lockingservice.MusicLockingService.java
License:Apache License
public void process(WatchedEvent event) { // Watcher interface if (event.getState() == KeeperState.SyncConnected) { connectedSignal.countDown();//from w w w .jav a2s .c om } }
From source file:com.bigdata.service.jini.AbstractServer.java
License:Open Source License
/** * Server startup reads {@link Configuration} data from the file or URL * named by <i>args</i> and applies any optional overrides, starts the * service, and advertises the service for discovery. Aside from the server * class to start, the behavior is more or less entirely parameterized by * the {@link Configuration}./*from ww w. ja v a 2s .co m*/ * * @param args * Either the command line arguments or the arguments from the * {@link ServiceDescriptor}. Either way they identify the jini * {@link Configuration} (you may specify either a file or URL) * and optional overrides for that {@link Configuration}. * @param lifeCycle * The life cycle object. This is used if the server is started * by the jini {@link ServiceStarter}. Otherwise specify a * {@link FakeLifeCycle}. * * @see NonActivatableServiceDescriptor */ protected AbstractServer(final String[] args, final LifeCycle lifeCycle) { // Show the copyright banner during startup. Banner.banner(); if (lifeCycle == null) throw new IllegalArgumentException(); this.lifeCycle = lifeCycle; setSecurityManager(); /* * Display the banner. * * Note: This also installs the UncaughtExceptionHandler. * * @see https://sourceforge.net/apps/trac/bigdata/ticket/601 */ Banner.banner(); // Thread.setDefaultUncaughtExceptionHandler( // new Thread.UncaughtExceptionHandler() { // public void uncaughtException(Thread t, Throwable e) { // log.warn("Uncaught exception in thread", e); // } // }); /* * Read jini configuration & service properties */ List<Entry> entries = null; final JiniClientConfig jiniClientConfig; try { config = ConfigurationProvider.getInstance(args); jiniClientConfig = new JiniClientConfig(getClass().getName(), config); /* * The zpath of the logical service. * * @todo null allowed if zookeeper not in use. make required if * zookeeper is a required integration, but then you will really * need to use the ServicesManager to start any service since the * zookeeper configuration needs to be established as well. */ logicalServiceZPath = (String) config.getEntry(getClass().getName(), ConfigurationOptions.LOGICAL_SERVICE_ZPATH, String.class, null/* default */); /* * Make sure that the parent directory exists. * * Note: the parentDir will be null if the serviceIdFile is in the * root directory or if it is specified as a filename without any * parents in the path expression. Note that the file names a file * in the current working directory in the latter case and the root * always exists in the former - and in both of those cases we do * not have to create the parent directory. */ serviceDir = (File) config.getEntry(getClass().getName(), ConfigurationOptions.SERVICE_DIR, File.class); if (serviceDir != null && !serviceDir.exists()) { log.warn("Creating: " + serviceDir); serviceDir.mkdirs(); } // The file on which the ServiceID will be written. serviceIdFile = new File(serviceDir, "service.id"); // The lock file. lockFile = new File(serviceDir, ".lock"); /* * Attempt to acquire an exclusive lock on a file in the same * directory as the serviceIdFile. */ acquireFileLock(); writePIDFile(pidFile = new File(serviceDir, "pid")); // convert Entry[] to a mutable list. entries = new LinkedList<Entry>(Arrays.asList(jiniClientConfig.entries)); /* * Make sure that there is a Name and Hostname associated with the * service. If a ServiceID was pre-assigned in the Configuration * then we will extract that also. */ { String serviceName = null; String hostname = null; UUID serviceUUID = null; for (Entry e : entries) { if (e instanceof Name && serviceName == null) { // found a name. serviceName = ((Name) e).name; } if (e instanceof Hostname && hostname == null) { hostname = ((Hostname) e).hostname; } if (e instanceof ServiceUUID && serviceUUID == null) { serviceUUID = ((ServiceUUID) e).serviceUUID; } } // if serviceName not given then set it now. if (serviceName == null) { // assign a default service name. final String defaultName = getClass().getName() + "@" + AbstractStatisticsCollector.fullyQualifiedHostName + "#" + hashCode(); serviceName = defaultName; // add to the Entry[]. entries.add(new Name(serviceName)); } // set the field on the class. this.serviceName = serviceName; // if hostname not given then set it now. if (hostname == null) { /* * @todo This is a best effort during startup and unchanging * thereafter. We should probably report all names for the * host and report the current names for the host. However * there are a number of issues where similar data are not * being updated which could lead to problems if host name * assignments were changed. */ hostname = AbstractStatisticsCollector.fullyQualifiedHostName; // add to the Entry[]. entries.add(new Hostname(hostname)); } // set the field on the class. this.hostname = hostname; // if serviceUUID assigned then set ServiceID from it now. if (serviceUUID != null) { // set serviceID. this.serviceID = JiniUtil.uuid2ServiceID(serviceUUID); if (!serviceIdFile.exists()) { // write the file iff it does not exist. writeServiceIDOnFile(this.serviceID); } } else if (!serviceIdFile.exists()) { /* * Since nobody assigned us a ServiceID and since there is * none on record in the [serviceIdFile], we assign one now * ourselves. */ // set serviceID. this.serviceID = JiniUtil.uuid2ServiceID(UUID.randomUUID()); // write the file iff it does not exist. writeServiceIDOnFile(this.serviceID); } } /* * Extract how the service will provision itself from the * Configuration. */ // The exporter used to expose the service proxy. exporter = (Exporter) config.getEntry(// getClass().getName(), // component ConfigurationOptions.EXPORTER, // name Exporter.class, // type (of the return object) /* * The default exporter is a BasicJeriExporter using a * TcpServerEnpoint. */ new BasicJeriExporter(TcpServerEndpoint.getInstance(0), new BasicILFactory())); if (serviceIdFile.exists()) { try { final ServiceID serviceIDFromFile = readServiceId(serviceIdFile); if (this.serviceID == null) { // set field on class. this.serviceID = serviceIDFromFile; } else if (!this.serviceID.equals(serviceIDFromFile)) { /* * This is a paranoia check on the Configuration and the * serviceIdFile. The ServiceID should never change so * these values should remain in agreement. */ throw new ConfigurationException( "ServiceID in Configuration does not agree with the value in " + serviceIdFile + " : Configuration=" + this.serviceID + ", serviceIdFile=" + serviceIDFromFile); } } catch (IOException ex) { fatal("Could not read serviceID from existing file: " + serviceIdFile + ": " + this, ex); } } else { if (log.isInfoEnabled()) log.info("New service instance."); } } catch (ConfigurationException ex) { fatal("Configuration error: " + this, ex); } /* * The runtime shutdown hook appears to be a robust way to handle ^C by * providing a clean service termination. * * Note: This is setup before we start any async threads, including * service discovery. */ Runtime.getRuntime().addShutdownHook(new ShutdownThread(this)); /* * Start the client - this provides a means to connect to the other * services running in the federation (it runs a DiscoveryManager to do * that). */ try { // new client - defer connection to fed. client = new JiniClient(getClass(), config); // // connect to the federation (starts service discovery for the client). // client.connect(); } catch (Throwable t) { fatal("Could not create JiniClient: " + this, t); } /* * Create the service object. */ JiniFederation<?> fed = null; try { /* * Note: By creating the service object here rather than outside of * the constructor we potentially create problems for subclasses of * AbstractServer since their own constructor will not have been * executed yet. * * Some of those problems are worked around using a JiniClient to * handle all aspects of service discovery (how this service locates * the other services in the federation). * * Note: If you explicitly assign values to those clients when the * fields are declared, e.g., [timestampServiceClient=null] then the * ctor will overwrite the values set by [newService] since it is * running before those initializations are performed. This is * really crufty, may be JVM dependent, and needs to be refactored * to avoid this subclass ctor init problem. */ if (log.isInfoEnabled()) log.info("Creating service impl..."); // init w/ client's properties. impl = newService(client.getProperties()); if (log.isInfoEnabled()) log.info("Service impl is " + impl); // Connect to the federation (starts service discovery for client). final JiniFederation<?> f = fed = client.connect(); /* * Add a watcher that will create the ephemeral znode for the * federation on zookeeper (re-)connect. * * Note: We don't have to do this once we have been connected, but * if the service starts without a zookeeper connection and then * later connects then it will otherwise fail to create its znode. */ fed.getZookeeperAccessor().addWatcher(new Watcher() { boolean sessionValid = false; public void process(WatchedEvent event) { switch (event.getState()) { case Expired: sessionValid = false; synchronized (AbstractServer.this) { /* * Synchronized so that creating and cancelling the * master election future are atomic. */ if (masterElectionFuture != null) { masterElectionFuture.cancel(true/* mayInterruptIfRunning */); masterElectionFuture = null; log.warn("Zookeeper session expired: cancelled master election task: " + this); } } break; case NoSyncConnected: case SyncConnected: if (!sessionValid) { sessionValid = true; if (serviceID != null) { try { notifyZookeeper(f, JiniUtil.serviceID2UUID(serviceID)); } catch (Throwable t) { log.error(AbstractServer.this, t); } } } } // switch } // process(event) }); // Watcher // start the service. if (impl instanceof AbstractService) { ((AbstractService) impl).start(); } } catch (Exception ex) { fatal("Could not start service: " + this, ex); } /* * Export a proxy object for this service instance. * * Note: This must be done before we start the join manager since the * join manager will register the proxy. */ try { proxy = exporter.export(impl); if (log.isInfoEnabled()) log.info("Proxy is " + proxy + "(" + proxy.getClass() + ")"); } catch (ExportException ex) { fatal("Export error: " + this, ex); } /* * Start the join manager. */ try { assert proxy != null : "No proxy?"; final Entry[] attributes = entries.toArray(new Entry[0]); if (this.serviceID != null) { /* * We read the serviceID from local storage (either the * serviceIDFile and/or the Configuration). */ joinManager = new JoinManager(proxy, // service proxy attributes, // attr sets serviceID, // ServiceID fed.getDiscoveryManagement(), // DiscoveryManager new LeaseRenewalManager(), // config); } else { /* * We are requesting a serviceID from the registrar. */ joinManager = new JoinManager(proxy, // service proxy attributes, // attr sets this, // ServiceIDListener fed.getDiscoveryManagement(), // DiscoveryManager new LeaseRenewalManager(), // config); } } catch (Exception ex) { fatal("JoinManager: " + this, ex); } /* * Note: This is synchronized in case set via listener by the * JoinManager, which would be rather fast action on its part. */ synchronized (this) { if (this.serviceID != null) { /* * Notify the service that it's service UUID has been set. * * @todo Several things currently depend on this notification. * In effect, it is being used as a proxy for the service * registration event. */ notifyServiceUUID(serviceID); } } }
From source file:com.bigdata.zookeeper.AbstractZNodeConditionWatcher.java
License:Open Source License
/** * Notify a {@link Thread} synchronized on itself when the znode that it is * watching generates an {@link WatchedEvent}. If the event is a * disconnect, then we instead set the {@link #disconnected} flag and return * immediately./* w w w .j a v a 2 s . com*/ */ public void process(final WatchedEvent event) { if (log.isInfoEnabled()) log.info(event.toString()); synchronized (this) { switch (event.getState()) { case Disconnected: // nothing to do until we are reconnected. disconnected = true; return; default: if (disconnected) { _resumeWatch(); } // fall through break; } boolean satisifed; try { satisifed = isConditionSatisfied(event); } catch (KeeperException e) { log.warn(this.toString(), e); return; } catch (InterruptedException e) { log.warn(this.toString(), e); return; } if (satisifed) { success(event.getType().toString()); return; } else { _resumeWatch(); } } }
From source file:com.bigdata.zookeeper.HierarchicalZNodeWatcher.java
License:Open Source License
/** * Note: Synchronized for mutex with {@link #cancel()}. *//*from w w w. j a v a2 s .c o m*/ synchronized public void process(final WatchedEvent event) { if (cancelled) { // ignore events once cancelled. return; } if (log.isInfoEnabled()) log.info(event.toString()); /* * Put ALL events in the queue. * * Note: This does NOT mean that the application will see all state * changes for watched znodes. Zookeeper DOES NOT provide that * guarantee. The application CAN miss events between the time that a * state change triggers a WatchedEvent and the time that the * application handles the event and resets the watch. */ queue.add(event); switch (event.getState()) { case Disconnected: return; default: break; } final String path = event.getPath(); switch (event.getType()) { case NodeCreated: /* * We always reset the watch when we see a NodeCreated event for a * znode that we are already watching. * * This event type can occur for the root of the watched hierarchy * since we set the watch regardless of the existence of the zroot. * * If the event occurs for a different znode then it may have been * deleted and re-created and we may have missed the delete event. */ try { zookeeper.exists(path, this); } catch (KeeperException e1) { log.error("path=" + path, e1); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } return; case NodeDeleted: /* * A watched znode was deleted. Unless this is the zroot, we will * remove our watch on the znode (the expectation is that the watch * will be re-established if the child is re-created since we will * notice the NodeChildrenChanged event). */ if (zroot.equals(path)) { try { zookeeper.exists(path, this); } catch (KeeperException e1) { log.error("path=" + path, e1); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } } else { watched.remove(path); removedWatch(path); } return; case NodeDataChanged: try { zookeeper.getData(path, this, new Stat()); } catch (KeeperException e1) { log.error("path=" + path, e1); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } return; case NodeChildrenChanged: /* * Get the children (and reset our watch on the path). */ try { acceptChildren(path, zookeeper.getChildren(event.getPath(), this)); } catch (KeeperException e) { log.error(this, e); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } return; default: return; } }
From source file:com.bigdata.zookeeper.TestZookeeperSessionSemantics.java
License:Open Source License
public void test_handleExpiredSession() throws InterruptedException, KeeperException, IOException { final String hosts = "localhost:" + clientPort; final Lock lock = new ReentrantLock(); final Condition expireCond = lock.newCondition(); final Condition connectCond = lock.newCondition(); final Condition disconnectCond = lock.newCondition(); final AtomicBoolean didExpire = new AtomicBoolean(false); final AtomicBoolean didDisconnect = new AtomicBoolean(false); /*/*from w w w . j av a 2 s. c om*/ * Start an instance and run until it gets an assigned sessionId. */ { final ZooKeeper zk1a = new ZooKeeper(hosts, requestedSessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { log.warn(event); } }); int i = 0; while (i < 10) { boolean done = false; if (zk1a.getState() == ZooKeeper.States.CONNECTED) { done = true; } log.info("zk.getState()=" + zk1a.getState() + ", zk.getSessionId()=" + zk1a.getSessionId()); if (done) break; Thread.sleep(500); i++; } if (zk1a.getState() != ZooKeeper.States.CONNECTED) { fail("Did not connect."); } zk1a.close(); } final ZooKeeper zk1 = new ZooKeeper(hosts, requestedSessionTimeout, new Watcher() { /** * Note: The default watcher will not receive any events * after a session expire. A {@link Zookeeper#close()} * causes an immediate session expire. Thus, no events * (include the session expire) will be received after a * close(). */ @Override public void process(final WatchedEvent event) { log.warn(event); switch (event.getState()) { case AuthFailed: break; case Disconnected: lock.lock(); try { didDisconnect.set(true); disconnectCond.signalAll(); } finally { lock.unlock(); } break; case Expired: lock.lock(); try { didExpire.set(true); expireCond.signalAll(); } finally { lock.unlock(); } break; // case ConnectedReadOnly: // not in 3.3.3 // break; // case NoSyncConnected: // not in 3.3.3 // break; // case SaslAuthenticated: // not in 3.3.3 // break; case SyncConnected: lock.lock(); try { connectCond.signalAll(); } finally { lock.unlock(); } break; case Unknown: break; } } }); /* * Note: You can not obtain the negotiated session timeout until the * zookeeper client has connected to a zookeeper service (or rather, * it will return ZERO until it is connected). */ final int negotiatedSessionTimeout; lock.lock(); try { log.info("Waiting zk connected."); connectCond.await(10, TimeUnit.SECONDS); negotiatedSessionTimeout = zk1.getSessionTimeout(); if (log.isInfoEnabled()) log.info("Negotiated sessionTimeout=" + negotiatedSessionTimeout); assertNotSame(0, negotiatedSessionTimeout); assertTrue(negotiatedSessionTimeout > 0); } finally { lock.unlock(); } assertTrue(zk1.getState().isAlive()); assertFalse(didDisconnect.get()); assertFalse(didExpire.get()); // clear out test znodes. destroyZNodes(zk1, "/test"); // ensure root /test znode exists. try { zk1.create("/test", new byte[] {}, acl, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException ex) { log.warn("Ignoring: " + ex); } // look at that znode, establishing a watcher. zk1.getData("/test", true/* watch */, null/* stat */); // update the znode's data. zk1.setData("/test", new byte[] { 1 }, -1/* version */); // create an ephemeral sequential znode that is a child of /test. final String foozpath = zk1.create("/test/foo", new byte[] {}, acl, CreateMode.EPHEMERAL_SEQUENTIAL); // create a 2nd ephemeral sequential znode that is a child of /test. final String foozpath2 = zk1.create("/test/foo", new byte[] {}, acl, CreateMode.EPHEMERAL_SEQUENTIAL); /* * Look at that znode, establishing a watcher. * * Note: We appear to see node deleted events for the ephemeral znodes * if the client connection is closed, but the state is still reported * as SyncConnected rather than SessionExpired. * * Note: If we do not establish a watcher for an ephemeral znode, then * we DO NOT see an node deleted event when the client is closed! */ zk1.getData(foozpath, true/* watch */, null/* stat */); // zk1.getData(foozpath2, true/* watch */, null/* stat */); //// close the existing instance. // log.info("Closing ZK client"); // zk1.close(); // log.fatal("killing local zookeeper service."); // killZKServer(); // Thread.sleep(5000); // fail("done"); if (false) { log.info("Spin loop awaiting !isAlive() for client."); final long begin = System.currentTimeMillis(); while (zk1.getState().isAlive()) { log.info("zk.getState()=" + zk1.getState() + ", zk.getSessionId()=" + zk1.getSessionId()); final long elapsed = System.currentTimeMillis() - begin; if (elapsed > 60000 * 2) fail("Client still isAlive()."); Thread.sleep(1000); } log.info("Continuing"); } if (true) { log.error("KILL ZOOKEEPER."); Thread.sleep(5000); log.info("Spin loop on ephemeral znode getData() for client."); while (true) { try { zk1.getData(foozpath, true/* watch */, null/* stat */); } catch (KeeperException ex) { log.error(ex, ex); Thread.sleep(1000); continue; } log.info("zk.getState()=" + zk1.getState() + ", zk.getSessionId()=" + zk1.getSessionId()); break; // final long elapsed = System.currentTimeMillis() - begin; // if (elapsed > 60000 * 2) // fail("Client still isAlive()."); // Thread.sleep(1000); } log.info("Continuing"); final byte[] a = zk1.getData(foozpath, true/* watch */, null/* stat */); assertTrue("Expected " + Arrays.toString(new byte[] { 1 }) + ", not " + Arrays.toString(a), BytesUtil.bytesEqual(new byte[] { 1 }, a)); } // // The disconnect event should be immediate. // lock.lock(); // try { // disconnectCond.await(100, TimeUnit.MILLISECONDS); // } finally { // lock.unlock(); // } // // assertTrue(didDisconnect.get()); assertFalse(didDisconnect.get()); assertFalse(didExpire.get()); assertFalse(zk1.getState().isAlive()); /* * Wait up to a little more than the negotiated session timeout for the * session to be expired. */ lock.lock(); try { // Attempt to get the znode again. new Thread(new Runnable() { public void run() { try { final byte[] tmp = zk1.getData("/test", true/* watch */, null/* stat */); } catch (KeeperException e) { log.error(e, e); } catch (InterruptedException e) { log.error(e, e); } } }).start(); expireCond.await(negotiatedSessionTimeout + 10000, TimeUnit.MILLISECONDS); /* * Note: No events are ever delivered to the watcher with * KeeperStates:=SessionExpired. This appears to be a design * decision. */ assertFalse(didExpire.get()); } finally { lock.unlock(); } /* * Now obtain a new session. */ { log.warn("Starting new ZK connection"); final ZooKeeper zk2 = new ZooKeeper(hosts, requestedSessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { log.warn(event); } }); assertTrue(zk2.getState().isAlive()); } }
From source file:com.bigdatafly.flume.zookeeper.Zookeeper.java
License:Apache License
/** * connect ZK, register Watch/unhandle Watch * /* www .j ava 2 s. c om*/ * @return */ public CuratorFramework mkClient(Map conf, List<String> servers, Object port, String root, final WatcherCallBack watcher) { CuratorFramework fk = newCurator(conf, servers, port, root); fk.getCuratorListenable().addListener(new CuratorListener() { public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception { if (e.getType().equals(CuratorEventType.WATCHED)) { WatchedEvent event = e.getWatchedEvent(); watcher.execute(event.getState(), event.getType(), event.getPath()); } } }); fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { public void unhandledError(String msg, Throwable error) { String errmsg = "Unrecoverable Zookeeper error, halting process: " + msg; LOG.error(errmsg, error); } }); fk.start(); return fk; }