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

The following examples show how to use org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent. 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: 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 #2
Source File: MetastorePluginWithHA.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)
    throws Exception {
  switch ( event.getType() ) {
  case CHILD_ADDED:
    PathsUpdate newUpdate = new PathsUpdate();
    PluginCacheSyncUtil.setUpdateFromChildEvent(event, newUpdate);
    metastorePlugin.processCacheNotification(newUpdate);
    break;
  case INITIALIZED:
  case CHILD_UPDATED:
  case CHILD_REMOVED:
    break;
  case CONNECTION_RECONNECTED:
    MetastoreAuthzBinding.setSentryCacheOutOfSync(false);
    break;
  case CONNECTION_SUSPENDED:
  case CONNECTION_LOST:
    MetastoreAuthzBinding.setSentryCacheOutOfSync(true);
    break;
  default:
    break;
  }
}
 
Example #3
Source File: ZkUtils.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
/**
     * 设置子节点更改监听
     *
     * @param path
     * @throws Exception
     */
    public boolean listenerPathChildrenCache(String path, BiConsumer<CuratorFramework, PathChildrenCacheEvent> biConsumer) {

        if (!ObjectUtils.allNotNull(zkClient, path, biConsumer)) {
            return Boolean.FALSE;
        }
        try {
            Stat stat = exists(path);
            if (stat != null) {
                PathChildrenCache watcher = new PathChildrenCache(zkClient, path, true);
                watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
                //该模式下 watcher在重连的时候会自动 rebuild 否则需要重新rebuild
                watcher.getListenable().addListener(biConsumer::accept, pool);
                if (!pathChildrenCaches.contains(watcher)) {
                    pathChildrenCaches.add(watcher);
                }
//                else{
//                    watcher.rebuild();
//                }
                return Boolean.TRUE;
            }
        } catch (Exception e) {
            log.error("listen path children cache fail! path:{} , error:{}", path, e);
        }
        return Boolean.FALSE;
    }
 
Example #4
Source File: OracleClient.java    From fluo with Apache License 2.0 6 votes vote down vote up
/**
 * It's possible an Oracle has gone into a bad state. Upon the leader being changed, we want to
 * update our state
 */
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event)
    throws Exception {

  if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)
      || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)
      || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) {

    Participant participant = leaderLatch.getLeader();
    synchronized (this) {
      if (isLeader(participant)) {
        currentLeader = leaderLatch.getLeader();
      } else {
        currentLeader = null;
      }
    }
  }
}
 
Example #5
Source File: StandbyNode.java    From niubi-job with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
    AssertHelper.isTrue(isJoined(), "illegal state .");
    boolean hasLeadership = leaderSelector != null && leaderSelector.hasLeadership();
    if (!hasLeadership) {
        return;
    }
    if (!EventHelper.isChildModifyEvent(event)) {
        return;
    }
    StandbyJobData standbyJobData = new StandbyJobData(event.getData());
    if (StringHelper.isEmpty(standbyJobData.getData().getJobOperation())) {
        return;
    }
    StandbyJobData.Data data = standbyJobData.getData();
    if (data.isUnknownOperation()) {
        return;
    }
    StandbyNodeData.Data nodeData = standbyApiFactory.nodeApi().getNode(nodePath).getData();
    executeOperation(nodeData, data);
}
 
Example #6
Source File: ZookeeperSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
private void processEvent(TaskDO taskDO, NamingService destNamingService, PathChildrenCacheEvent event, String path,
    Map<String, String> queryParam) throws NacosException {
    Map<String, String> ipAndPortParam = parseIpAndPortString(path);
    Instance instance = buildSyncInstance(queryParam, ipAndPortParam, taskDO);
    switch (event.getType()) {
        case CHILD_ADDED:
        case CHILD_UPDATED:

            destNamingService.registerInstance(
                getServiceNameFromCache(taskDO.getTaskId(), queryParam), instance);
            break;
        case CHILD_REMOVED:

            destNamingService.deregisterInstance(
                getServiceNameFromCache(taskDO.getTaskId(), queryParam),
                ipAndPortParam.get(INSTANCE_IP_KEY),
                Integer.parseInt(ipAndPortParam.get(INSTANCE_PORT_KEY)));
            nacosServiceNameMap.remove(taskDO.getTaskId());
            break;
        default:
            break;
    }
}
 
Example #7
Source File: SessionRepository.java    From vespa with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
    zkWatcherExecutor.execute(() -> {
        log.log(Level.FINE, () -> "Got child event: " + event);
        switch (event.getType()) {
            case CHILD_ADDED:
                sessionsChanged();
                synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
                break;
            case CHILD_REMOVED:
            case CONNECTION_RECONNECTED:
                sessionsChanged();
                break;
        }
    });
}
 
Example #8
Source File: MockCurator.java    From vespa with Apache License 2.0 6 votes vote down vote up
/** Creates a node below the given directory root */
private String createNode(String pathString, byte[] content, boolean createParents, CreateMode createMode, Node root, Listeners listeners)
        throws KeeperException.NodeExistsException, KeeperException.NoNodeException {
    validatePath(pathString);
    Path path = Path.fromString(pathString);
    if (path.isRoot()) return "/"; // the root already exists
    Node parent = root.getNode(Paths.get(path.getParentPath().toString()), createParents);
    String name = nodeName(path.getName(), createMode);

    if (parent == null)
        throw new KeeperException.NoNodeException(path.getParentPath().toString());
    if (parent.children().containsKey(path.getName()))
        throw new KeeperException.NodeExistsException(path.toString());

    parent.add(name).setContent(content);
    String nodePath = "/" + path.getParentPath().toString() + "/" + name;
    listeners.notify(Path.fromString(nodePath), content, PathChildrenCacheEvent.Type.CHILD_ADDED);
    return nodePath;
}
 
Example #9
Source File: DDLChildListener.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    ClusterDelayProvider.delayAfterGetDdlNotice();
    ChildData childData = event.getData();
    switch (event.getType()) {
        case CHILD_ADDED:
            try {
                lockTableByNewNode(childData);
            } catch (Exception e) {
                LOGGER.warn("CHILD_ADDED error", e);
            }
            break;
        case CHILD_UPDATED:
            updateMeta(childData);
            break;
        case CHILD_REMOVED:
            deleteNode(childData);
            break;
        default:
            break;
    }
}
 
Example #10
Source File: UpdateForwarderWithHA.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void childEvent(CuratorFramework client,
    PathChildrenCacheEvent event) throws Exception {
  switch ( event.getType() ) {
  case CHILD_ADDED:
    K newUpdate = (K) baseUpdate.getClass().newInstance();
    PluginCacheSyncUtil.setUpdateFromChildEvent(event, newUpdate);
    updateForwarder.postNotificationToLog(newUpdate);
    break;
  case INITIALIZED:
  case CHILD_UPDATED:
  case CHILD_REMOVED:
    break;
  case CONNECTION_RECONNECTED:
    // resume the node
    SentryPlugin.instance.setOutOfSync(false);
    break;
  case CONNECTION_SUSPENDED:
  case CONNECTION_LOST:
    // suspend the node
    SentryPlugin.instance.setOutOfSync(true);
    break;
  default:
    break;
  }
}
 
Example #11
Source File: ClusterSyncManager.java    From Decision with Apache License 2.0 6 votes vote down vote up
public String updateNodeStatus(String nodeId, PathChildrenCacheEvent.Type eventType) throws Exception {

        String clusterStatus = null;

        switch (eventType){

            case CHILD_ADDED:
                logger.info("ClusterSyncManager Leader: {}. STATUS - Group Initialized: {} ", groupId, nodeId);
                clusterNodesStatus.get(NODE_STATUS.INITIALIZED).add(nodeId);
                clusterNodesStatus.get(NODE_STATUS.STOPPED).remove(nodeId);
                break;
            case CHILD_REMOVED:
                logger.error("*****ClusterSyncManager Leader: {}.  STATUS - Group {} are notified as DOWN *****",
                        groupId, nodeId);
                clusterNodesStatus.get(NODE_STATUS.INITIALIZED).remove(nodeId);
                clusterNodesStatus.get(NODE_STATUS.STOPPED).add(nodeId);
                break;
        }


        return updateNodeStatus();

    }
 
Example #12
Source File: NodeDiscovery.java    From curator-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) {
    String nodePath = null;
    T nodeData = null;
    if (event.getData() != null) {
        nodePath = event.getData().getPath();
        nodeData = parseChildData(event.getData());
    }
    switch (event.getType()) {
        case CHILD_ADDED:
            addNode(nodePath, nodeData);
            break;

        case CHILD_REMOVED:
            removeNode(nodePath, nodeData);
            break;

        case CHILD_UPDATED:
            updateNode(nodePath, nodeData);
            break;
    }
}
 
Example #13
Source File: ZooKeeperCommandExecutor.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework unused, PathChildrenCacheEvent event) throws Exception {
    if (event.getType() != PathChildrenCacheEvent.Type.CHILD_ADDED) {
        return;
    }

    final long lastKnownRevision = revisionFromPath(event.getData().getPath());
    try {
        replayLogs(lastKnownRevision);
    } catch (ReplicationException ignored) {
        // replayLogs() logs and handles the exception already, so we just bail out here.
        return;
    }

    oldLogRemover.touch();
}
 
Example #14
Source File: ClusterPathChildrenCacheListener.java    From Decision with Apache License 2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
{
    String node;
    String nodeId;

    try {
        node = ZKPaths.getNodeFromPath(event.getData().getPath());
        nodeId = node.substring(node.indexOf("_") + 1);

        clusterSyncManagerInstance.updateNodeStatus(nodeId, event.getType());

    }catch (Exception e){
        logger.error("Exception receiving event {}: {}", event, e.getMessage());
    }

}
 
Example #15
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 #16
Source File: MonitorNodeServerService.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
private void removeEvent(PathChildrenCacheEvent event) {
    String key = toKey(event);
    NodeServerInfo data = toNodeServerInfo(event);
    log.debug(" Monitor node event remove! key:{}, data:{}", key, data);
    if (monitorNodeServerPool.containsKey(key)) {
        monitorNodeServerPool.remove(key);
    }

}
 
Example #17
Source File: CuratorMasterLatch.java    From zookeeper-book-example with Apache License 2.0 5 votes vote down vote up
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) {
    if(event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
        try{
            assignTask(event.getData().getPath().replaceFirst("/tasks/", ""),
                    event.getData().getData());
        } catch (Exception e) {
            LOG.error("Exception when assigning task.", e);
        }   
    }
}
 
Example #18
Source File: ClusterSyncManagerTest.java    From Decision with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateNodeStatusShouldBeInitialized() throws Exception {

    doNothing().when(zkUtils).createEphemeralZNode(anyString(), any(byte[].class));
    when(zkUtils.existZNode(contains("group1"))).thenReturn(false);
    when(zkUtils.existZNode(contains("group2"))).thenReturn(false);

    clusterSyncManager.initializedGroupStatus();
    clusterSyncManager.updateNodeStatus("group1", PathChildrenCacheEvent.Type.CHILD_ADDED);
    String status = clusterSyncManager.updateNodeStatus("group2", PathChildrenCacheEvent.Type.CHILD_ADDED);

    assertEquals(STREAMING.ZK_EPHEMERAL_NODE_STATUS_INITIALIZED, status);

}
 
Example #19
Source File: SwitchCleanListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override public void childEvent(CuratorFramework curatorFramework,
        PathChildrenCacheEvent event) throws Exception {
    switch (event.getType()) {
        case CHILD_ADDED:
             checkSwitch(event);
            break;
        default:
            break;
    }
}
 
Example #20
Source File: SwitchCommitListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework curatorFramework,
                       PathChildrenCacheEvent event) throws Exception {
    switch (event.getType()) {
        case CHILD_ADDED:
            checkCommit(event);
            break;
        default:
            break;
    }
}
 
Example #21
Source File: TenantRepository.java    From vespa with Apache License 2.0 5 votes vote down vote up
private void childEvent(CuratorFramework framework, PathChildrenCacheEvent event) {
    switch (event.getType()) {
        case CHILD_ADDED:
        case CHILD_REMOVED:
            updateTenants();
            break;
    }
}
 
Example #22
Source File: MigrateTaskWatch.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private boolean isTaskErrorOrSucess(PathChildrenCacheEvent event) {
    try {
        TaskNode pTaskNode = new Gson().fromJson(new String(event.getData().getData()), TaskNode.class);
        if (pTaskNode.getStatus() >= 4) {
            return true;
        }
    } catch (Exception e) {

    }

    return false;
}
 
Example #23
Source File: MigrateTaskWatch.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework curatorFramework,
                       PathChildrenCacheEvent event) throws Exception {
    switch (event.getType()) {
        case CHILD_ADDED:
            if (isTaskErrorOrSucess(event)) break;
            addOrUpdate(event);
            String path = event.getData().getPath() + "/_prepare";
            if (curatorFramework.checkExists().forPath(path) == null) {
                curatorFramework.create().creatingParentsIfNeeded().forPath(path);
            }
            ZKUtils.addChildPathCache(path, new SwitchPrepareListener());

            String commitPath = event.getData().getPath() + "/_commit";
            if (curatorFramework.checkExists().forPath(commitPath) == null) {
                curatorFramework.create().creatingParentsIfNeeded().forPath(commitPath);
            }
            ZKUtils.addChildPathCache(commitPath, new SwitchCommitListener());


            String cleanPath = event.getData().getPath() + "/_clean";
            if (curatorFramework.checkExists().forPath(cleanPath) == null) {
                curatorFramework.create().creatingParentsIfNeeded().forPath(cleanPath);
            }
            ZKUtils.addChildPathCache(cleanPath, new SwitchCleanListener());
            LOGGER.info("table CHILD_ADDED: " + event.getData().getPath());
            break;
        case CHILD_UPDATED:
            if (isTaskErrorOrSucess(event)) break;
            addOrUpdate(event);
            LOGGER.info("CHILD_UPDATED: " + event.getData().getPath());
            break;
        default:
            break;
    }
}
 
Example #24
Source File: MasterSlaveNode.java    From niubi-job with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    AssertHelper.isTrue(isJoined(), "illegal state .");
    //对Master权限进行双重检查
    if (!leaderSelector.hasLeadership()) {
        return;
    }
    if (EventHelper.isChildRemoveEvent(event)) {
        MasterSlaveNodeData masterSlaveNodeData = new MasterSlaveNodeData(event.getData().getPath(), event.getData().getData());
        releaseJobs(masterSlaveNodeData.getPath(), masterSlaveNodeData.getData());
    }
}
 
Example #25
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 #26
Source File: CommandPathListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    switch (event.getType()) {
    case CHILD_ADDED:
        // 在发生节点添加的时候,则执行接收命令并执行
        // 1,首先检查
        String path = event.getData().getPath();
        String basePath = ZKUtils.getZKBasePath() + ZKHandler.ZK_NODE_PATH + "/";

        // 检查节点与当前的节点是否一致
        String node = path.substring(basePath.length());

        if (node.equals(ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID))) {
            // 检查命令内容是否为
            if (ZKHandler.RELOAD_FROM_ZK.equals(new String(client.getData().forPath(path)))) {
                // 从服务器上下载最新的配制文件信息
                ZktoXmlMain.ZKLISTENER.notifly(ZkNofiflyCfg.ZK_NOTIFLY_LOAD_ALL.getKey());
                // 重新加载配制信息
                reload(path);
                // 完成之后,删除命令信息, 以供下次读取
                client.delete().forPath(event.getData().getPath());
                LOGGER.info("CommandPathListener path:" + path + " reload success");
            }
        }

        break;
    case CHILD_UPDATED:
        break;
    case CHILD_REMOVED:
        break;
    default:
        break;
    }

}
 
Example #27
Source File: EventDispatcher.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void childEvent(final CuratorFramework client, final PathChildrenCacheEvent event) throws Exception {
  final PathChildrenCacheEvent.Type original = event.getType();
  final TransientStoreEventType mapped = MAPPINGS.get(original);
  if (mapped != null) { // dispatch the event to listeners only if it can be mapped
    final String path = event.getData().getPath();
    final byte[] bytes = event.getData().getData();
    final V value = store.getConfig().getSerializer().deserialize(bytes);
    store.fireListeners(TransientStoreEvent.of(mapped, path, value));
  }
}
 
Example #28
Source File: RuleFunctionCacheListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    ChildData data = event.getData();
    switch (event.getType()) {

        case CHILD_ADDED:
            addOrUpdate();
            break;
        case CHILD_UPDATED:
            addOrUpdate();
            break;
        default:
            break;
    }
}
 
Example #29
Source File: PartitionManager.java    From fluo with Apache License 2.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
  switch (event.getType()) {
    case CHILD_ADDED:
    case CHILD_REMOVED:
    case CHILD_UPDATED:
      scheduleUpdate();
      break;
    default:
      break;
  }
}
 
Example #30
Source File: MockCurator.java    From vespa with Apache License 2.0 5 votes vote down vote up
/** sets the data of an existing node */
private void setData(String pathString, byte[] content, Node root, Listeners listeners)
        throws KeeperException.NoNodeException {
    validatePath(pathString);
    getNode(pathString, root).setContent(content);
    listeners.notify(Path.fromString(pathString), content, PathChildrenCacheEvent.Type.CHILD_UPDATED);
}