Search in sources :

Example 26 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project archaius by Netflix.

the class ZooKeeperConfigurationSource method start.

/**
 * Adds a listener to the pathChildrenCache, initializes the cache, then starts the cache-management background thread
 *
 * @throws Exception
 */
public void start() throws Exception {
    // create the watcher for future configuration updatess
    pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

        public void childEvent(CuratorFramework aClient, PathChildrenCacheEvent event) throws Exception {
            Type eventType = event.getType();
            ChildData data = event.getData();
            String path = null;
            if (data != null) {
                path = data.getPath();
                // scrub configRootPath out of the key name
                String key = removeRootPath(path);
                byte[] value = data.getData();
                String stringValue = new String(value, charset);
                logger.debug("received update to pathName [{}], eventType [{}]", path, eventType);
                logger.debug("key [{}], and value [{}]", key, stringValue);
                // fire event to all listeners
                Map<String, Object> added = null;
                Map<String, Object> changed = null;
                Map<String, Object> deleted = null;
                if (eventType == Type.CHILD_ADDED) {
                    added = new HashMap<String, Object>(1);
                    added.put(key, stringValue);
                } else if (eventType == Type.CHILD_UPDATED) {
                    changed = new HashMap<String, Object>(1);
                    changed.put(key, stringValue);
                } else if (eventType == Type.CHILD_REMOVED) {
                    deleted = new HashMap<String, Object>(1);
                    deleted.put(key, stringValue);
                }
                WatchedUpdateResult result = WatchedUpdateResult.createIncremental(added, changed, deleted);
                fireEvent(result);
            }
        }
    });
    // passing true to trigger an initial rebuild upon starting.  (blocking call)
    pathChildrenCache.start(true);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Type(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) HashMap(java.util.HashMap) ChildData(org.apache.curator.framework.recipes.cache.ChildData) HashMap(java.util.HashMap) Map(java.util.Map) IOException(java.io.IOException) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException) NodeExistsException(org.apache.zookeeper.KeeperException.NodeExistsException) WatchedUpdateResult(com.netflix.config.WatchedUpdateResult)

Example 27 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project kylin by apache.

the class ZookeeperDistributedLock method watchLocks.

@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;
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ZkReleaseLockInterruptException(org.apache.kylin.job.lock.zookeeper.exception.ZkReleaseLockInterruptException) ZkReleaseLockException(org.apache.kylin.job.lock.zookeeper.exception.ZkReleaseLockException) KeeperException(org.apache.zookeeper.KeeperException) ZkPeekLockException(org.apache.kylin.job.lock.zookeeper.exception.ZkPeekLockException) ZkAcquireLockException(org.apache.kylin.job.lock.zookeeper.exception.ZkAcquireLockException) ZkPeekLockInterruptException(org.apache.kylin.job.lock.zookeeper.exception.ZkPeekLockInterruptException)

Example 28 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project curator by apache.

the class PathCacheExample method addListener.

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);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)

Example 29 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project sofa-rpc by sofastack.

the class ZookeeperRegistry method subscribe.

@Override
public List<ProviderGroup> subscribe(final ConsumerConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isSubscribe()) {
        // 注册中心不订阅
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return null;
    }
    // 订阅如果有必要
    subscribeConsumerUrls(config);
    if (config.isSubscribe()) {
        List<ProviderInfo> matchProviders;
        // 订阅配置
        if (!INTERFACE_CONFIG_CACHE.containsKey(buildConfigPath(rootPath, config))) {
            // 订阅接口级配置
            subscribeConfig(config, config.getConfigListener());
        }
        if (!INTERFACE_OVERRIDE_CACHE.containsKey(buildOverridePath(rootPath, config))) {
            // 订阅IP级配置
            subscribeOverride(config, config.getConfigListener());
        }
        // 订阅Providers节点
        try {
            if (providerObserver == null) {
                // 初始化
                providerObserver = new ZookeeperProviderObserver();
            }
            final String providerPath = buildProviderPath(rootPath, config);
            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_SUB, providerPath));
            }
            PathChildrenCache pathChildrenCache = INTERFACE_PROVIDER_CACHE.get(config);
            if (pathChildrenCache == null) {
                // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
                ProviderInfoListener providerInfoListener = config.getProviderInfoListener();
                providerObserver.addProviderListener(config, providerInfoListener);
                // TODO 换成监听父节点变化(只是监听变化了,而不通知变化了什么,然后客户端自己来拉数据的)
                pathChildrenCache = new PathChildrenCache(zkClient, providerPath, true);
                final PathChildrenCache finalPathChildrenCache = pathChildrenCache;
                pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

                    @Override
                    public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
                        if (LOGGER.isDebugEnabled(config.getAppName())) {
                            LOGGER.debugWithApp(config.getAppName(), "Receive zookeeper event: " + "type=[" + event.getType() + "]");
                        }
                        switch(event.getType()) {
                            case // 加了一个provider
                            CHILD_ADDED:
                                providerObserver.addProvider(config, providerPath, event.getData(), finalPathChildrenCache.getCurrentData());
                                break;
                            case // 删了一个provider
                            CHILD_REMOVED:
                                providerObserver.removeProvider(config, providerPath, event.getData(), finalPathChildrenCache.getCurrentData());
                                break;
                            case // 更新一个Provider
                            CHILD_UPDATED:
                                providerObserver.updateProvider(config, providerPath, event.getData(), finalPathChildrenCache.getCurrentData());
                                break;
                            default:
                                break;
                        }
                    }
                });
                pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
                INTERFACE_PROVIDER_CACHE.put(config, pathChildrenCache);
            }
            List<ProviderInfo> providerInfos = ZookeeperRegistryHelper.convertUrlsToProviders(providerPath, pathChildrenCache.getCurrentData());
            matchProviders = ZookeeperRegistryHelper.matchProviderInfos(config, providerInfos);
        } catch (Exception e) {
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SUB_PROVIDER, EXT_NAME), e);
        }
        if (EventBus.isEnable(ConsumerSubEvent.class)) {
            ConsumerSubEvent event = new ConsumerSubEvent(config);
            EventBus.post(event);
        }
        return Collections.singletonList(new ProviderGroup().addAll(matchProviders));
    }
    return null;
}
Also used : PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) ProviderInfoListener(com.alipay.sofa.rpc.listener.ProviderInfoListener) ConsumerSubEvent(com.alipay.sofa.rpc.event.ConsumerSubEvent) KeeperException(org.apache.zookeeper.KeeperException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) CuratorFramework(org.apache.curator.framework.CuratorFramework) ProviderInfo(com.alipay.sofa.rpc.client.ProviderInfo) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ProviderGroup(com.alipay.sofa.rpc.client.ProviderGroup)

Example 30 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project sofa-rpc by sofastack.

the class ZookeeperRegistry method subscribeOverride.

/**
 * 订阅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 // 新增IP级配置
                    CHILD_ADDED:
                        overrideObserver.addConfig(config, overridePath, event.getData());
                        break;
                    case // 删除IP级配置
                    CHILD_REMOVED:
                        overrideObserver.removeConfig(config, overridePath, event.getData(), registerConfig);
                        break;
                    case // 更新IP级配置
                    CHILD_UPDATED:
                        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);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) AbstractInterfaceConfig(com.alipay.sofa.rpc.config.AbstractInterfaceConfig) KeeperException(org.apache.zookeeper.KeeperException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)

Aggregations

PathChildrenCacheEvent (org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)65 CuratorFramework (org.apache.curator.framework.CuratorFramework)55 PathChildrenCacheListener (org.apache.curator.framework.recipes.cache.PathChildrenCacheListener)49 PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)34 ChildData (org.apache.curator.framework.recipes.cache.ChildData)20 IOException (java.io.IOException)15 KeeperException (org.apache.zookeeper.KeeperException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 Test (org.junit.Test)10 DataSegment (org.apache.druid.timeline.DataSegment)5 ZKPaths (org.apache.curator.utils.ZKPaths)4 RedisConfig (cn.northpark.zookeeper.RedisConfig)3 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)3 ServiceInstance (com.baidu.brpc.client.channel.ServiceInstance)3 RpcException (com.baidu.brpc.exceptions.RpcException)3 DataSegment (io.druid.timeline.DataSegment)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Releasable (com.ctrip.xpipe.api.lifecycle.Releasable)2