org.apache.curator.framework.recipes.cache.PathChildrenCacheListener Java Examples

The following examples show how to use org.apache.curator.framework.recipes.cache.PathChildrenCacheListener. 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: MasterSlaveJobSummaryListener.java    From niubi-job with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void listen() throws Exception {
    MasterSlaveApiFactory masterSlaveApiFactory = new MasterSlaveApiFactoryImpl(client);
    PathChildrenCache pathChildrenCache = new PathChildrenCache(client, masterSlaveApiFactory.pathApi().getJobPath(), true);
    pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
        @Override
        public synchronized void childEvent(CuratorFramework clientInner, PathChildrenCacheEvent event) throws Exception {
            if (!EventHelper.isChildUpdateEvent(event) && !EventHelper.isChildAddEvent(event)) {
                return;
            }
            MasterSlaveJobData masterSlaveJobData = new MasterSlaveJobData(event.getData());
            if (!masterSlaveJobData.getData().isOperated()) {
                return;
            }
            LoggerHelper.info("begin update master-slave job summary " + masterSlaveJobData.getData());
            masterSlaveJobSummaryService.updateJobSummary(masterSlaveJobData.getData());
            masterSlaveJobLogService.updateJobLog(masterSlaveJobData.getData());
            LoggerHelper.info("update master-slave job summary successfully " + masterSlaveJobData.getData());
        }
    });
    pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
}
 
Example #2
Source File: ZKMasterController.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * create the listener for ephemeral worker znodes to determine worker joins and failures
 */
private void addEphemChildrenCacheListener(PathChildrenCache cache) {
  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      switch (event.getType()) {
        case CHILD_ADDED:
          workerZnodeAdded(event);
          break;

        case CHILD_REMOVED:
          workerZnodeRemoved(event);
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example #3
Source File: ZKMasterController.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * create the listener for persistent worker znodes to determine worker status changes
 */
private void addPersChildrenCacheListener(PathChildrenCache cache) {
  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      switch (event.getType()) {

        case CHILD_UPDATED:
          childZnodeUpdated(event);
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example #4
Source File: ZKWorkerController.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * listen for additions to the job events directory in zk server
 * @param cache
 */
private void addEventsChildrenCacheListener(PathChildrenCache cache) {
  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      switch (event.getType()) {
        case CHILD_ADDED:
          eventPublished(event);
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example #5
Source File: ZKUtils.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public static void addChildPathCache(String path, PathChildrenCacheListener listener) {
    NameableExecutor businessExecutor = MycatServer.getInstance().getBusinessExecutor();
    ExecutorService executor = businessExecutor == null ? Executors.newFixedThreadPool(5) : businessExecutor;

    try {
        /**
         * 监听子节点的变化情况
         */
        final PathChildrenCache childrenCache = new PathChildrenCache(getConnection(), path, true);
        childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        childrenCache.getListenable().addListener(listener, executor);
        watchMap.put(path, childrenCache);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: StandbyJobSummaryListener.java    From niubi-job with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void listen() throws Exception {
    StandbyApiFactory standbyApiFactory = new StandbyApiFactoryImpl(client);
    PathChildrenCache pathChildrenCache = new PathChildrenCache(client, standbyApiFactory.pathApi().getJobPath(), true);
    pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
        @Override
        public synchronized void childEvent(CuratorFramework clientInner, PathChildrenCacheEvent event) throws Exception {
            if (!EventHelper.isChildUpdateEvent(event) && !EventHelper.isChildAddEvent(event)) {
                return;
            }
            StandbyJobData standbyJobData = new StandbyJobData(event.getData());
            if (!standbyJobData.getData().isOperated()) {
                return;
            }
            LoggerHelper.info("begin update standby job summary " + standbyJobData.getData());
            standbyJobSummaryService.updateJobSummary(standbyJobData.getData());
            standbyJobLogService.updateJobLog(standbyJobData.getData());
            LoggerHelper.info("update standby job summary successfully " + standbyJobData.getData());
        }
    });
    pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
}
 
Example #7
Source File: MetaServerAssignmentHolder.java    From hermes with Apache License 2.0 6 votes vote down vote up
private void initPathChildrenCache() throws InitializationException {
	m_pathChildrenCache = new PathChildrenCache(m_zkClient.get(), ZKPathUtils.getMetaServerAssignmentRootZkPath(),
	      true);

	m_pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

		@Override
		public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
			if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED
			      || event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED
			      || event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
				String topic = ZKPathUtils.lastSegment(event.getData().getPath());
				m_topiAssignmentCache.invalidate(topic);
			}
		}
	});

	try {
		m_pathChildrenCache.start(StartMode.BUILD_INITIAL_CACHE);
	} catch (Exception e) {
		throw new InitializationException("Init metaServerAssignmentHolder failed.", e);
	}
}
 
Example #8
Source File: ClusterZKImpl.java    From pravega with Apache License 2.0 6 votes vote down vote up
private PathChildrenCacheListener pathChildrenCacheListener(final ClusterListener listener) {
    return (client, event) -> {
        log.debug("Event {} generated on cluster", event);
        switch (event.getType()) {
            case CHILD_ADDED:
                log.info("Node {} added to cluster", getServerName(event));
                listener.onEvent(HOST_ADDED, Host.fromBytes(event.getData().getData()));
                break;
            case CHILD_REMOVED:
                log.info("Node {} removed from cluster", getServerName(event));
                listener.onEvent(HOST_REMOVED, Host.fromBytes(event.getData().getData()));
                break;
            case CHILD_UPDATED:
                log.warn("Invalid usage: Node {} updated externally for cluster", getServerName(event));
                break;
            case CONNECTION_LOST:
                log.error("Connection lost with Zookeeper");
                listener.onEvent(ERROR, null);
                break;
            //$CASES-OMITTED$
            default:
                log.warn("Received unknown event {}", event.getType());
        }
    };
}
 
Example #9
Source File: ZookeeperSyncToNacosServiceImplTest.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
public boolean mockSync(TaskDO taskDO) throws Exception {
    List<ChildData> childDataList = spy(ArrayList.class);
    ListenerContainer<PathChildrenCacheListener> listeners = mock(ListenerContainer.class);
    childDataList.add(new ChildData(TEST_PATH, null, null));
    when(taskDO.getTaskId()).thenReturn(TEST_TASK_ID);
    when(taskDO.getSourceClusterId()).thenReturn(TEST_SOURCE_CLUSTER_ID);
    when(taskDO.getDestClusterId()).thenReturn(TEST_DEST_CLUSTER_ID);
    CuratorFramework curatorFramework = mock(CuratorFramework.class);
    doReturn(curatorFramework).when(zookeeperServerHolder).get(any(), any());
    doReturn(destNamingService).when(nacosServerHolder).get(any(), any());
    doReturn(pathChildrenCache).when(zookeeperSyncToNacosService).getPathCache(any());
    when(pathChildrenCache.getCurrentData()).thenReturn(childDataList);
    doReturn(ClusterTypeEnum.ZK).when(skyWalkerCacheServices).getClusterType(any());
    when(pathChildrenCache.getListenable()).thenReturn(listeners);
    return zookeeperSyncToNacosService.sync(taskDO);
}
 
Example #10
Source File: CuratorFacade.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个路径节点缓存,返回之前已调用{@link PathChildrenCache#start()},
 * 你需要在使用完之后调用{@link PathChildrenCache#close()}关闭缓存节点;
 * 如果你忘记关闭,那么会在curator关闭的时候统一关闭。
 * 更多线程安全问题,请查看类文档中提到的笔记。
 *
 * @param path     父节点
 * @param listener 缓存事件监听器,运行在逻辑线程,不必考虑线程安全。
 * @return PathChildrenCache 不再使用时需要手动关闭!不要使用{@link PathChildrenCache}获取数据
 * @throws Exception zk errors
 */
public CloseableHandle watchChildren(String path, @Nonnull PathChildrenCacheListener listener) throws Exception {
    // CloseableExecutorService这个还是不共享的好
    CloseableExecutorService watcherService = clientMgr.newClosableExecutorService();
    // 指定pathChildrenCache接收事件的线程,复用线程池,以节省开销。
    PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true, false, watcherService);

    // 先添加listener以确保不会遗漏事件 --- 使用EventLoop线程监听,消除同步,listener不必考虑线程安全问题。
    pathChildrenCache.getListenable().addListener(listener, appEventLoop);
    // 避免外部忘记关闭
    this.allocateNodeCache.add(pathChildrenCache);

    // 启动缓存
    pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);
    return new CloseableHandle(pathChildrenCache);
}
 
Example #11
Source File: PathCacheExample.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
private static void addListener(PathChildrenCache cache) {
	// a PathChildrenCacheListener is optional. Here, it's used just to log
	// changes
	PathChildrenCacheListener listener = new PathChildrenCacheListener() {
		@Override
		public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
			switch (event.getType()) {
			case CHILD_ADDED: {
				System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()) + ", value: "
						+ new String(event.getData().getData()));
				break;
			}
			case CHILD_UPDATED: {
				System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()) + ", value: "
						+ new String(event.getData().getData()));
				break;
			}
			case CHILD_REMOVED: {
				System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
				break;
			}
			default:
				break;
			}
		}
	};
	cache.getListenable().addListener(listener);
}
 
Example #12
Source File: ZKClientImpl.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> listenChildrenPath(final String parent, final NodeListener listener, final boolean sync)
        throws Exception {
    PathChildrenCache cache = new PathChildrenCache(client, parent, false, false, EVENT_THREAD_POOL);
    cache.getListenable().addListener(new PathChildrenCacheListener() {
        @Override
        public void childEvent(CuratorFramework c, PathChildrenCacheEvent e)
                throws Exception {
            if (e.getData() == null) { return; }
            switch (e.getType()) {
                case CHILD_ADDED:
                    listener.nodeChanged(ZKClientImpl.this,
                                         new ChangedEvent(e.getData().getPath(), ChangedEvent.Type.CHILD_ADDED));
                    break;
                case CHILD_REMOVED:
                    listener.nodeChanged(ZKClientImpl.this,
                                         new ChangedEvent(e.getData().getPath(), ChangedEvent.Type.CHILD_REMOVED));
                    break;
                case CHILD_UPDATED:
                    listener.nodeChanged(ZKClientImpl.this,
                                         new ChangedEvent(e.getData().getPath(), ChangedEvent.Type.CHILD_UPDATED));
                    break;
            }
        }
    }, SAME_EXECUTOR);
    PathChildrenCache.StartMode mode = sync ? PathChildrenCache.StartMode.BUILD_INITIAL_CACHE : PathChildrenCache.StartMode.NORMAL;
    cache.start(mode);
    List<ChildData> children = cache.getCurrentData();
    List<String> result = new ArrayList<String>();
    for (ChildData child : children) {
        result.add(child.getPath());
    }
    return result;
}
 
Example #13
Source File: ZKUtils.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public static void addViewPathCache(String path, PathChildrenCacheListener listener) {
    try {
        //watch the child status
        final PathChildrenCache childrenCache = new PathChildrenCache(getConnection(), path, true);
        childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        childrenCache.getListenable().addListener(listener);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: ZKUtils.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public static void addChildPathCache(String path, PathChildrenCacheListener listener) {
    try {
        //watch the child status
        final PathChildrenCache childrenCache = new PathChildrenCache(getConnection(), path, true);
        childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        childrenCache.getListenable().addListener(listener);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: MigrateTaskWatch.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static void start() {
    String migratePath = ZKUtils.getZKBasePath() + "migrate";
    // modify by jian.xie,cjw,zwy 如果migrate 启动的时候不存在,无法监听,需要这里监听一次
    // 如果第一次没有migrate节点这里应该无法使用集群 还需优化
    try {
        CuratorFramework client = ZKUtils.getConnection();
        if (client.checkExists().forPath(migratePath) == null) {
            client.create().creatingParentsIfNeeded().forPath(migratePath);
        }
    }catch (Exception e){
        throw new RuntimeException(e);
    }
    ZKUtils.addChildPathCache(migratePath, new PathChildrenCacheListener() {
        @Override
        public void childEvent(CuratorFramework curatorFramework,
                               PathChildrenCacheEvent fevent) throws Exception {

            switch (fevent.getType()) {
                case CHILD_ADDED:
                    LOGGER.info("table CHILD_ADDED: " + fevent.getData().getPath());
                    ZKUtils.addChildPathCache(fevent.getData().getPath(), new TaskPathChildrenCacheListener());
                    break;
                default:
                    break;
            }
        }
    });

}
 
Example #16
Source File: ZookeeperDistributedLock.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Closeable watchLocks(String lockPathRoot, Executor executor, final Watcher watcher) {
    PathChildrenCache cache = new PathChildrenCache(curator, lockPathRoot, true);
    try {
        cache.start();
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                case CHILD_ADDED:
                    watcher.onLock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                case CHILD_REMOVED:
                    watcher.onUnlock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                default:
                    break;
                }
            }
        }, executor);
    } catch (Exception ex) {
        logger.error("Error to watch lock path " + lockPathRoot, ex);
    }
    return cache;
}
 
Example #17
Source File: PathCacheExample.java    From curator with Apache License 2.0 5 votes vote down vote up
private static void addListener(PathChildrenCache cache)
{
    // a PathChildrenCacheListener is optional. Here, it's used just to log changes
    PathChildrenCacheListener listener = new PathChildrenCacheListener()
    {
        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
        {
            switch ( event.getType() )
            {
                case CHILD_ADDED:
                {
                    System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                    break;
                }

                case CHILD_UPDATED:
                {
                    System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                    break;
                }

                case CHILD_REMOVED:
                {
                    System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                    break;
                }
            }
        }
    };
    cache.getListenable().addListener(listener);
}
 
Example #18
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 订阅IP级配置(服务发布暂时不支持动态配置,暂时支持订阅ConsumerConfig参数设置)
 *
 * @param config   consumer config
 * @param listener config listener
 */
protected void subscribeOverride(final ConsumerConfig config, ConfigListener listener) {
    try {
        if (overrideObserver == null) { // 初始化
            overrideObserver = new ZookeeperOverrideObserver();
        }
        overrideObserver.addConfigListener(config, listener);
        final String overridePath = buildOverridePath(rootPath, config);
        final AbstractInterfaceConfig registerConfig = getRegisterConfig(config);
        // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, overridePath, true);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
                if (LOGGER.isDebugEnabled(config.getAppName())) {
                    LOGGER.debug("Receive zookeeper event: " + "type=[" + event.getType() + "]");
                }
                switch (event.getType()) {
                    case CHILD_ADDED: //新增IP级配置
                        overrideObserver.addConfig(config, overridePath, event.getData());
                        break;
                    case CHILD_REMOVED: //删除IP级配置
                        overrideObserver.removeConfig(config, overridePath, event.getData(), registerConfig);
                        break;
                    case CHILD_UPDATED:// 更新IP级配置
                        overrideObserver.updateConfig(config, overridePath, event.getData());
                        break;
                    default:
                        break;
                }
            }
        });
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        INTERFACE_OVERRIDE_CACHE.put(overridePath, pathChildrenCache);
        overrideObserver.updateConfigAll(config, overridePath, pathChildrenCache.getCurrentData());
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SUB_PROVIDER_OVERRIDE, EXT_NAME), e);
    }
}
 
Example #19
Source File: ZookeeperDistributedLock.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Closeable watchLocks(String lockPathRoot, Executor executor, final Watcher watcher) {
    PathChildrenCache cache = new PathChildrenCache(curator, lockPathRoot, true);
    try {
        cache.start();
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                case CHILD_ADDED:
                    watcher.onLock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                case CHILD_REMOVED:
                    watcher.onUnlock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                default:
                    break;
                }
            }
        }, executor);
    } catch (Exception ex) {
        logger.error("Error to watch lock path " + lockPathRoot, ex);
    }
    return cache;
}
 
Example #20
Source File: PathCacheExample.java    From xian with Apache License 2.0 5 votes vote down vote up
private static void addListener(PathChildrenCache cache)
{
    // a PathChildrenCacheListener is optional. Here, it's used just to log changes
    PathChildrenCacheListener listener = new PathChildrenCacheListener()
    {
        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
        {
            switch ( event.getType() )
            {
                case CHILD_ADDED:
                {
                    System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                    break;
                }

                case CHILD_UPDATED:
                {
                    System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                    break;
                }

                case CHILD_REMOVED:
                {
                    System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
                    break;
                }
            }
        }
    };
    cache.getListenable().addListener(listener);
}
 
Example #21
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 订阅接口级配置
 *
 * @param config   provider/consumer config
 * @param listener config listener
 */
protected void subscribeConfig(final AbstractInterfaceConfig config, ConfigListener listener) {
    try {
        if (configObserver == null) { // 初始化
            configObserver = new ZookeeperConfigObserver();
        }
        configObserver.addConfigListener(config, listener);
        final String configPath = buildConfigPath(rootPath, config);
        // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, configPath, true);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
                if (LOGGER.isDebugEnabled(config.getAppName())) {
                    LOGGER.debug("Receive zookeeper event: " + "type=[" + event.getType() + "]");
                }
                switch (event.getType()) {
                    case CHILD_ADDED: //新增接口级配置
                        configObserver.addConfig(config, configPath, event.getData());
                        break;
                    case CHILD_REMOVED: //删除接口级配置
                        configObserver.removeConfig(config, configPath, event.getData());
                        break;
                    case CHILD_UPDATED:// 更新接口级配置
                        configObserver.updateConfig(config, configPath, event.getData());
                        break;
                    default:
                        break;
                }
            }
        });
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        INTERFACE_CONFIG_CACHE.put(configPath, pathChildrenCache);
        configObserver.updateConfigAll(config, configPath, pathChildrenCache.getCurrentData());
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SUB_PROVIDER_CONFIG, EXT_NAME), e);
    }
}
 
Example #22
Source File: ZKBarrierHandler.java    From twister2 with Apache License 2.0 5 votes vote down vote up
/**
 * create the listener for barrier event znodes in the barrier directory
 * to determine whether all workers arrived on the barrier
 */
private void addBarrierChildrenCacheListener(
    PathChildrenCache cache,
    JobMasterAPI.BarrierType barrierType) {

  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      String childPath = event.getData().getPath();
      int workerID = ZKUtils.getWorkerIDFromPersPath(childPath);
      long timeout = Longs.fromByteArray(event.getData().getData());

      switch (event.getType()) {
        case CHILD_ADDED:
          if (barrierType == JobMasterAPI.BarrierType.DEFAULT) {
            barrierMonitor.arrivedAtDefault(workerID, timeout);
          } else if (barrierType == JobMasterAPI.BarrierType.INIT) {
            barrierMonitor.arrivedAtInit(workerID, timeout);
          }
          break;

        case CHILD_REMOVED:
          if (barrierType == JobMasterAPI.BarrierType.DEFAULT) {
            barrierMonitor.removedFromDefault(workerID);
          } else if (barrierType == JobMasterAPI.BarrierType.INIT) {
            barrierMonitor.removedFromInit(workerID);
          }
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example #23
Source File: ClusterStateHolder.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void startLeaderLatchPathChildrenCache() throws InitializationException {
	try {
		m_leaderLatchPathChildrenCache = new PathChildrenCache(m_client.get(), ZKPathUtils.getMetaServersZkPath(),
		      true);

		m_leaderLatchPathChildrenCache.getListenable().addListener(
		      new PathChildrenCacheListener() {

			      @Override
			      public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				      if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED
				            || event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED
				            || event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
					      updateLeaderInfo();
				      }
			      }
		      },
		      Executors.newSingleThreadExecutor(HermesThreadFactory.create(
		            "LeaderLatchPathChildrenCacheListenerExecutor", true)));

		m_leaderLatchPathChildrenCache.start(StartMode.BUILD_INITIAL_CACHE);
	} catch (Exception e) {
		throw new InitializationException("Init metaServer leaderLatch parent pathChildrenCache failed.", e);
	}

	updateLeaderInfo();
}
 
Example #24
Source File: Zk.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param path
 * @param pathChildrenCacheListener
 * @throws Exception
 */
@SuppressWarnings("resource")
public static void addPathChildrenCacheListener(String path, PathChildrenCacheListener pathChildrenCacheListener) throws Exception {
	PathChildrenCache cache = new PathChildrenCache(zkclient, path, true);
	cache.start();

	//		System.out.println("监听开始/zk........");
	//		PathChildrenCacheListener plis = new PathChildrenCacheListener()
	//		{
	//
	//			@Override
	//			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
	//			{
	//				switch (event.getType())
	//				{
	//				case CHILD_ADDED:
	//				{
	//					System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
	//					break;
	//				}
	//
	//				case CHILD_UPDATED:
	//				{
	//					System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
	//					break;
	//				}
	//
	//				case CHILD_REMOVED:
	//				{
	//					System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
	//					break;
	//				}
	//				}
	//
	//			}
	//		};
	//		//注册监听 
	cache.getListenable().addListener(pathChildrenCacheListener);

}
 
Example #25
Source File: LeaderInitEventHandler.java    From hermes with Apache License 2.0 4 votes vote down vote up
protected MetaServerListListener(long version, ListenerContainer<PathChildrenCacheListener> listenerContainer) {
	super(version, listenerContainer);
}
 
Example #26
Source File: LeaderInitEventHandler.java    From hermes with Apache License 2.0 4 votes vote down vote up
protected void addMetaServerListListener(long version) throws Exception {
	ListenerContainer<PathChildrenCacheListener> listenerContainer = m_metaServerListCache.getListenable();
	listenerContainer.addListener(new MetaServerListListener(version, listenerContainer), m_eventBus.getExecutor());
}
 
Example #27
Source File: BasePathChildrenCacheListener.java    From hermes with Apache License 2.0 4 votes vote down vote up
protected BasePathChildrenCacheListener(long version, ListenerContainer<PathChildrenCacheListener> listenerContainer) {
	m_version = version;
	m_eventBus = PlexusComponentLocator.lookup(EventBus.class);
	m_clusterStateHolder = PlexusComponentLocator.lookup(ClusterStateHolder.class);
	m_listenerContainer = listenerContainer;
}
 
Example #28
Source File: AlarmEPLManager.java    From nightwatch with GNU Lesser General Public License v3.0 4 votes vote down vote up
public AlarmEPLManager(Map conf, CountDownLatch latch) {

        this.conf = conf;
        this.latch = latch;
        this.configuration = new Configuration();
        this.addMethods(configuration);
        this.addDbs();


        this.epService = EPServiceProviderManager.getDefaultProvider(configuration);
        this.admin = epService.getEPAdministrator();

        this.addSchemas();
        this.addEpls();
        this.start();
        curator = CuratorFrameworkFactory
                .newClient(com.jzsec.rtc.config.Configuration.getConfig().getString("rtc.zk.hosts"),
                        Utils.getInt(conf.get(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT)),
                        Utils.getInt(conf.get(Config.STORM_ZOOKEEPER_CONNECTION_TIMEOUT)),
                        new RetryNTimes(
                                Utils.getInt(conf.get(Config.STORM_ZOOKEEPER_RETRY_TIMES)),
                                Utils.getInt(conf.get(Config.STORM_ZOOKEEPER_RETRY_INTERVAL))
                        ));
        curator.start();
        createPath();
        ExecutorService pool = Executors.newFixedThreadPool(2);
        final PathChildrenCache pathChildrenCache = new PathChildrenCache(curator, "/alarm", true);
        try {
            pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
                public void childEvent(CuratorFramework framework,
                                       PathChildrenCacheEvent event) throws Exception {
                    List<ChildData> childDataList = pathChildrenCache.getCurrentData();
                    if(event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED || event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
                        if (childDataList != null && childDataList.size() > 0) {
                            // update and reload single rule  by businessScope in future
                            List<Map<Object, Object>> zkDataList = new ArrayList<Map<Object, Object>>();
                            for (ChildData childData : childDataList) {
                                LOG.info("==" + childData.getPath() + " changed," + new String(childData.getData(), "UTF-8"));
                                String data = new String(childData.getData(), "UTF-8");
                                if(!StringUtils.isEmpty(data)) {
                                    System.out.println("==" + childData.getPath() + " changed," + new String(childData.getData(), "UTF-8"));
                                    Map<Object, Object> zkData = (Map<Object, Object>) JSONValue.parse(data);
                                    zkDataList.add(zkData);
                                }

                            }
                            if(zkDataList.size() > 0) refresh(zkDataList);
                        }
                    }
                }
            }, pool);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example #29
Source File: ZooKeeperBucketService.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Override
public void startBucketChangeListener() {
    PathChildrenCacheListener bucketListener = (client, event) -> {
        StreamImpl stream;
        switch (event.getType()) {
            case CHILD_ADDED:
            case CHILD_UPDATED:
                stream = bucketStore.getStreamFromPath(event.getData().getPath());
                notify(new StreamNotification(stream.getScope(), stream.getStreamName(), NotificationType.StreamAdded));
                break;
            case CHILD_REMOVED:
                stream = bucketStore.getStreamFromPath(event.getData().getPath());
                notify(new StreamNotification(stream.getScope(), stream.getStreamName(), NotificationType.StreamRemoved));
                break;
            case CONNECTION_LOST:
                notify(new StreamNotification(null, null, NotificationType.ConnectivityError));
                break;
            default:
                log.warn("Received unknown event {} on bucket", event.getType(), getBucketId());
        }
    };
    
    PathChildrenCache pathChildrenCache = cacheRef.updateAndGet(existing -> {
        if (existing == null) {
            PathChildrenCache cache = bucketStore.getBucketPathChildrenCache(getServiceType(), getBucketId());

            cache.getListenable().addListener(bucketListener);
            log.info("bucket {} change notification listener registered", getBucketId());
            return cache;
        } else {
            return existing;
        }
    });

    try {
        pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);
    } catch (Exception e) {
        log.error("{}: Starting listener on bucket {} threw exception", getServiceType(), getBucketId(), e);
        throw Exceptions.sneakyThrow(e);
    }
}
 
Example #30
Source File: MockCurator.java    From vespa with Apache License 2.0 4 votes vote down vote up
public void add(Path path, PathChildrenCacheListener listener) {
    directoryListeners.put(path, listener);
}