org.apache.zookeeper.WatchedEvent Java Examples

The following examples show how to use org.apache.zookeeper.WatchedEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZkClient.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
private void processDataOrChildChange(WatchedEvent event) {
    final String path = event.getPath();

    if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) {
        Set<IZkChildListener> childListeners = _childListener.get(path);
        if (childListeners != null && !childListeners.isEmpty()) {
            fireChildChangedEvents(path, childListeners);
        }
    }

    if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) {
        Set<IZkDataListener> listeners = _dataListener.get(path);
        if (listeners != null && !listeners.isEmpty()) {
            fireDataChangedEvents(event.getPath(), listeners);
        }
    }
}
 
Example #2
Source File: HandleHolder.java    From xian with Apache License 2.0 6 votes vote down vote up
private void internalClose() throws Exception
{
    try
    {
        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();
    }
}
 
Example #3
Source File: WatchCallBack.java    From BigDataArchitect with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {

    switch (event.getType()) {
        case None:
            break;
        case NodeCreated:
            zk.getData("/AppConf",this,this,"sdfs");

            break;
        case NodeDeleted:
            //容忍性
            conf.setConf("");
            cc = new CountDownLatch(1);
            break;
        case NodeDataChanged:
            zk.getData("/AppConf",this,this,"sdfs");

            break;
        case NodeChildrenChanged:
            break;
    }

}
 
Example #4
Source File: ZKOperations.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Watch for the given path until it exists.
 * @param zkClient The {@link ZKClient} to use.
 * @param path A ZooKeeper path to watch for existent.
 */
private static void watchExists(final ZKClient zkClient, final String path, final SettableFuture<String> completion) {
  Futures.addCallback(zkClient.exists(path, new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      if (!completion.isDone()) {
        watchExists(zkClient, path, completion);
      }
    }
  }), new FutureCallback<Stat>() {
    @Override
    public void onSuccess(Stat result) {
      if (result != null) {
        completion.set(path);
      }
    }

    @Override
    public void onFailure(Throwable t) {
      completion.setException(t);
    }
  });
}
 
Example #5
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void processDataOrChildChange(WatchedEvent event) {
    final String path = event.getPath();

    if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) {
        Set<IZkChildListener> childListeners = _childListener.get(path);
        if (childListeners != null && !childListeners.isEmpty()) {
            fireChildChangedEvents(path, childListeners);
        }
    }

    if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) {
        Set<IZkDataListener> listeners = _dataListener.get(path);
        if (listeners != null && !listeners.isEmpty()) {
            fireDataChangedEvents(event.getPath(), listeners);
        }
    }
}
 
Example #6
Source File: AbstractZKServiceController.java    From twill with Apache License 2.0 6 votes vote down vote up
protected final void watchInstanceNode() {
  if (!shouldProcessZKEvent()) {
    return;
  }
  Futures.addCallback(zkClient.getData(getInstancePath(), new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      if (!shouldProcessZKEvent()) {
        return;
      }
      switch (event.getType()) {
        case NodeDataChanged:
          watchInstanceNode();
          break;
        case NodeDeleted:
          instanceNodeFailed(KeeperException.create(KeeperException.Code.NONODE, getInstancePath()));
          break;
        default:
          LOG.info("Ignore ZK event for instance node: {}", event);
      }
    }
  }), instanceNodeDataCallback, Threads.SAME_THREAD_EXECUTOR);
}
 
Example #7
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private void handleNodeDelete(int lockEpoch, final WatchedEvent event) {
    executeLockAction(lockEpoch, new LockAction() {
        @Override
        public void execute() {
            // The lock is either expired or closed
            if (!lockState.inState(State.WAITING)) {
                LOG.info("{} ignore watched node {} deleted event, since lock state has moved to {}.",
                        new Object[] { lockId, event.getPath(), lockState.getState() });
                return;
            }
            lockState.transition(State.PREPARED);

            // we don't need to wait and check the result, since:
            // 1) if it claimed the ownership, it would notify the waiters when claimed ownerships
            // 2) if it failed, it would also notify the waiters, the waiters would cleanup the state.
            checkLockOwnerAndWaitIfPossible(watcher, true);
        }

        @Override
        public String getActionName() {
            return "handleNodeDelete(path=" + event.getPath() + ")";
        }
    });
}
 
Example #8
Source File: ZkUtil.java    From java-study with Apache License 2.0 6 votes vote down vote up
public void process(WatchedEvent watchedEvent) {
    if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { //与zk服务器处于连接状态
    	//如果没有就创建
        if(watchedEvent.getType() == Event.EventType.None && null == watchedEvent.getPath()) {
        	
        }else if(watchedEvent.getType() == Event.EventType.NodeCreated) { 
            System.out.println("监控到了该节点被创建");
        } else if(watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            // 节点的子节点列表发生变化
        	System.out.println("监控到了该节点更新");
        } else if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
            // 节点的数据内容发生变化
        	System.out.println("监控到了该节点的子节点更新");
        }else if(watchedEvent.getType() == Event.EventType.NodeDeleted) {
            System.out.println("监控到了该节点删除");
        }
    }
}
 
Example #9
Source File: CdcrBufferStateManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  if (isCancelled) return; // if the watcher is cancelled, do nothing.
  String collectionName = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
  String shard = core.getCoreDescriptor().getCloudDescriptor().getShardId();

  log.info("The CDCR buffer state has changed: {} @ {}:{}", event, collectionName, shard);
  // session events are not change events, and do not remove the watcher
  if (Event.EventType.None.equals(event.getType())) {
    return;
  }
  SolrZkClient zkClient = core.getCoreContainer().getZkController().getZkClient();
  try {
    CdcrParams.BufferState state = CdcrParams.BufferState.get(zkClient.getData(CdcrBufferStateManager.this.getZnodePath(), watcher, null, true));
    log.info("Received new CDCR buffer state from watcher: {} @ {}:{}", state, collectionName, shard);
    CdcrBufferStateManager.this.setState(state);
  } catch (KeeperException | InterruptedException e) {
    log.warn("Failed synchronising new state @ {}:{}", collectionName, shard, e);
  }
}
 
Example #10
Source File: ZkClient.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
private void processStateChanged(WatchedEvent event) {
    logger.info("zookeeper state changed (" + event.getState() + ")");
    setCurrentState(event.getState());
    if (getShutdownTrigger()) {
        return;
    }
    try {
        fireStateChangedEvent(event.getState());

        if (event.getState() == KeeperState.Expired) {
            reconnect();
            fireNewSessionEvents();
        }
    } catch (final Exception e) {
        throw new RuntimeException("Exception while restarting zk client", e);
    }
}
 
Example #11
Source File: ZKManager.java    From uncode-schedule with GNU General Public License v2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
    zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
            .toString()), Integer.parseInt(this.properties
            .getProperty(keys.zkSessionTimeout.toString())),
            new Watcher() {
                public void process(WatchedEvent event) {
                    sessionEvent(connectionLatch, event);
                }
            });
    String authString = this.properties.getProperty(keys.userName.toString())
            + ":"+ this.properties.getProperty(keys.password.toString());
    zk.addAuthInfo("digest", authString.getBytes());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
            DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #12
Source File: ZkDistributedSemaphore.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void onEvent(WatchedEvent event) {

    if(event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
      Collection<UpdateListener> col = new ArrayList<>(listeners.keySet());
      for(UpdateListener l : col) {
        l.updated();
      }
    } else if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected){
      // re set the watcher after a disconnect.
      try {
        setWatcher();
      } catch (Exception e) {
        logger.error("Failure while re-setting watcher after reconnect.", e);
      }
    }
  }
 
Example #13
Source File: BaseClient.java    From opensharding-spi-impl with Apache License 2.0 6 votes vote down vote up
private void createNamespace(final byte[] date) throws KeeperException, InterruptedException {
    if (rootExist) {
        return;
    }
    try {
        if (null == holder.getZooKeeper().exists(rootNode, false)) {
            holder.getZooKeeper().create(rootNode, date, authorities, CreateMode.PERSISTENT);
        }
        rootExist = true;
    } catch (final KeeperException.NodeExistsException ex) {
        rootExist = true;
        return;
    }
    holder.getZooKeeper().exists(rootNode, WatcherCreator.deleteWatcher(new ZookeeperEventListener(rootNode) {
        
        @Override
        public void process(final WatchedEvent event) {
            rootExist = false;
        }
    }));
}
 
Example #14
Source File: Holder.java    From opensharding-spi-impl with Apache License 2.0 6 votes vote down vote up
private Watcher startWatcher() {
    return new Watcher() {
        
        @Override
        public void process(final WatchedEvent event) {
            processConnection(event);
            if (!isConnected()) {
                return;
            }
            processGlobalListener(event);
            // TODO filter event type or path
            if (event.getType() == Event.EventType.None) {
                return;
            }
            if (Event.EventType.NodeDeleted == event.getType() || checkPath(event.getPath())) {
                processUsualListener(event);
            }
        }
    };
}
 
Example #15
Source File: ZKManager.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
	zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
			.toString()), Integer.parseInt(this.properties
			.getProperty(keys.zkSessionTimeout.toString())),
			new Watcher() {
				public void process(WatchedEvent event) {
					sessionEvent(connectionLatch, event);
				}
			});
	String authString = this.properties.getProperty(keys.userName.toString())
			+ ":"+ this.properties.getProperty(keys.password.toString());
	this.isCheckParentPath = Boolean.parseBoolean(this.properties.getProperty(keys.isCheckParentPath.toString(),"true"));
	zk.addAuthInfo("digest", authString.getBytes());
	acl.clear();
	acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
			DigestAuthenticationProvider.generateDigest(authString))));
	acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #16
Source File: ZookeeperRegistry.java    From Distributed-KV with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
	// 传来NONE类型事件,一般是连接事件等
	if(event.getType() == EventType.None) {
		// 事件状态为:连接中
		if(event.getState() == KeeperState.SyncConnected) {
			// 唤醒等待连接成功的线程
			mutex.lock();
			try {
				// 唤醒等待连接成功的线程
				connCondition.signalAll();
			} finally {
				mutex.unlock();
			}
		}
	}
	
}
 
Example #17
Source File: OverseerTaskQueue.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  // session events are not change events, and do not remove the watcher
  if (Event.EventType.None.equals(event.getType())) {
    return;
  }
  // If latchEventType is not null, only fire if the type matches
  if (log.isDebugEnabled()) {
    log.debug("{} fired on path {} state {} latchEventType {}", event.getType(), event.getPath(), event.getState(), latchEventType);
  }
  if (latchEventType == null || event.getType() == latchEventType) {
    lock.lock();
    try {
      this.event = event;
      eventReceived.signalAll();
    } finally {
      lock.unlock();
    }
  }
}
 
Example #18
Source File: LocalZooKeeperCache.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Got Local ZooKeeper WatchedEvent: EventType: {}, KeeperState: {}, Path: {}", event.getType(),
                event.getState(), event.getPath());
    }
    if (event.getType() == Event.EventType.None) {
        switch (event.getState()) {
        case Expired:
            // in case of expired, the zkSession is no longer good
            LOG.warn("Lost connection from local ZK. Invalidating the whole cache.");
            dataCache.synchronous().invalidateAll();
            childrenCache.synchronous().invalidateAll();
            return;
        default:
            break;
        }
    }
    super.process(event, updater);
}
 
Example #19
Source File: NamespaceWatcher.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event)
{
    if ( client != null )
    {
        if ( actualWatcher != null )
        {
            actualWatcher.process(new NamespaceWatchedEvent(client, event));
        }
        else if ( curatorWatcher != null )
        {
            try
            {
                curatorWatcher.process(new NamespaceWatchedEvent(client, event));
            }
            catch ( Exception e )
            {
                ThreadUtils.checkInterrupted(e);
                client.logError("Watcher exception", e);
            }
        }
    }
}
 
Example #20
Source File: BKLogHandler.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    if (Watcher.Event.EventType.None.equals(event.getType())) {
        if (event.getState() == Watcher.Event.KeeperState.Expired) {
            // if the watcher is expired
            scheduler.schedule(new WatcherGetLedgersCallback(getFullyQualifiedName()),
                    conf.getZKRetryBackoffStartMillis(), TimeUnit.MILLISECONDS);
        }
    } else if (Watcher.Event.EventType.NodeChildrenChanged.equals(event.getType())) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("LogSegments Changed under {}.", getFullyQualifiedName());
        }
        asyncGetLedgerListWithRetries(LogSegmentMetadata.COMPARATOR, filter,
                getChildrenWatcher, new WatcherGetLedgersCallback(getFullyQualifiedName()));
    }
}
 
Example #21
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private void handleNodeDelete(int lockEpoch, final WatchedEvent event) {
    executeLockAction(lockEpoch, new LockAction() {
        @Override
        public void execute() {
            // The lock is either expired or closed
            if (!lockState.inState(State.WAITING)) {
                LOG.info("{} ignore watched node {} deleted event, since lock state has moved to {}.",
                        new Object[] { lockId, event.getPath(), lockState.getState() });
                return;
            }
            lockState.transition(State.PREPARED);

            // we don't need to wait and check the result, since:
            // 1) if it claimed the ownership, it would notify the waiters when claimed ownerships
            // 2) if it failed, it would also notify the waiters, the waiters would cleanup the state.
            checkLockOwnerAndWaitIfPossible(watcher, true);
        }

        @Override
        public String getActionName() {
            return "handleNodeDelete(path=" + event.getPath() + ")";
        }
    });
}
 
Example #22
Source File: TestCurrentInprogress.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private static ZooKeeper connectZooKeeper(String ensemble)
    throws IOException, KeeperException, InterruptedException {
  final CountDownLatch latch = new CountDownLatch(1);

  ZooKeeper zkc = new ZooKeeper(HOSTPORT, 3600, new Watcher() {
    public void process(WatchedEvent event) {
      if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
        latch.countDown();
      }
    }
  });
  if (!latch.await(10, TimeUnit.SECONDS)) {
    throw new IOException("Zookeeper took too long to connect");
  }
  return zkc;
}
 
Example #23
Source File: BaseClientTest.java    From opensharding-spi-impl with Apache License 2.0 6 votes vote down vote up
private ZookeeperEventListener buildListener(final IZookeeperClient client, final List<String> actual) {
    return new ZookeeperEventListener(null) {
        
        @Override
        public void process(final WatchedEvent event) {
            switch (event.getType()) {
                case NodeDataChanged:
                case NodeChildrenChanged:
                    try {
                        actual.add("update_" + event.getPath() + "_" + client.getDataString(event.getPath()));
                    } catch (final KeeperException | InterruptedException ignored) {
                    }
                    break;
                case NodeDeleted:
                    actual.add("delete_" + event.getPath() + "_");
                    break;
                default:
            }
        }
    };
}
 
Example #24
Source File: NativeZookeeperRegistryCenter.java    From opensharding-spi-impl with Apache License 2.0 6 votes vote down vote up
@Override
public void watch(final String key, final DataChangedEventListener eventListener) {
    String path = key + "/";
    if (!caches.containsKey(path)) {
        addCacheData(key);
    }
    PathTree cache = caches.get(path);
    cache.watch(new ZookeeperEventListener() {
        
        @Override
        public void process(final WatchedEvent event) {
            if (!Strings.isNullOrEmpty(event.getPath())) {
                eventListener.onChange(new DataChangedEvent(event.getPath(), getWithoutCache(event.getPath()), getEventChangedType(event)));
            }
        }
    });
}
 
Example #25
Source File: ZkWatcher.java    From zkclient with Apache License 2.0 5 votes vote down vote up
/**
 * 处理事件:会话超时,连接断开,节点变化等
 *
 * @param event
 */
public void process(WatchedEvent event) {
    switch (event.getState()) {
        case ConnectedReadOnly:
        case SyncConnected:
            if (!zkClient.isConnection()) {
                zkClient.setIsConnection(true);
                connLock.release();//连接成功
                LOGGER.warn("Zookeeper connection or retry success......");
            }
            break;
        case Expired://会话超时
            this.stateChange(event.getState());
            resetSession();
            break;
        case Disconnected://连接断开
            zkClient.setIsConnection(false);
            this.stateChange(event.getState());
            LOGGER.warn("Zookeeper connection break......");
            break;
        default:
            LOGGER.warn("Zookeeper state: " + event.getState());
            break;
    }
    switch (event.getType()) {
        case NodeChildrenChanged: //子节点变化
            this.childChange(event.getPath());
            break;
        case NodeDataChanged: //节点数据变化
            this.dataChange(event.getPath());
    }

}
 
Example #26
Source File: ZKWatcherProcess.java    From zkclient with Apache License 2.0 5 votes vote down vote up
/**
 * 处理子节点变化事件
 * @param event 
 * @return void
 */
public void processChildChanged(final WatchedEvent event){
    final String path = event.getPath();
    final Set<ZKListener> listeners = client.getChildListenerMap().get(path);
    //提交事件监听进行处理
    submitChildEvent(listeners,path,event.getType());
}
 
Example #27
Source File: LeaderElection.java    From twill with Apache License 2.0 5 votes vote down vote up
private Watcher wrapWatcher(final Watcher watcher) {
  return new Watcher() {
    @Override
    public void process(final WatchedEvent event) {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          watcher.process(event);
        }
      });
    }
  };
}
 
Example #28
Source File: TestActiveStandbyElector.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * verify becomeStandby is not called if already in standby
 */
@Test
public void testSuccessiveStandbyCalls() {
  elector.joinElection(data);

  // make the object go into the monitoring standby state
  elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK,
      ZK_LOCK_NAME);
  Mockito.verify(mockApp, Mockito.times(1)).becomeStandby();
  verifyExistCall(1);

  WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class);
  Mockito.when(mockEvent.getPath()).thenReturn(ZK_LOCK_NAME);

  // notify node deletion
  // monitoring should be setup again after event is received
  Mockito.when(mockEvent.getType()).thenReturn(Event.EventType.NodeDeleted);
  elector.processWatchEvent(mockZK, mockEvent);
  // is standby. no need to notify anything now
  Mockito.verify(mockApp, Mockito.times(0)).enterNeutralMode();
  // another joinElection called.
  Mockito.verify(mockZK, Mockito.times(2)).create(ZK_LOCK_NAME, data,
      Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK);
  // lost election
  elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK,
      ZK_LOCK_NAME);
  // still standby. so no need to notify again
  Mockito.verify(mockApp, Mockito.times(1)).becomeStandby();
  // monitor is set again
  verifyExistCall(2);
}
 
Example #29
Source File: Quorum.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    try {
        if (event.getType() == EventType.NodeChildrenChanged) {
            refreshNodes();
        }
    }
    catch (Exception x) {
        _log.error("error from zookeeper", x);
    }
}
 
Example #30
Source File: ZookeeperWatcher.java    From shark with Apache License 2.0 5 votes vote down vote up
@Override
public void process(WatchedEvent event) {
	if (null == zk_client)
		return;
	try {
		Thread.sleep(100);
		/* 重新注册节点 */
		zk_client.exists(nodePath, this);
		EventType eventType = event.getType();
		switch (eventType) {
		case NodeCreated:
			logger.info("create node-->" + event.getPath());
			break;
		case NodeDataChanged:
			final String nodePathValue = new String(zk_client.getData(nodePath, false, null));
			RegisterDataSource.register(nodePathValue, "zookeeper");
			logger.info("change node data-->" + event.getPath());
			break;
		case NodeChildrenChanged:
			break;
		case NodeDeleted:
		default:
			break;
		}
	} catch (Exception e) {
		throw new ConnectionException(e.toString());
	}
}