Java Code Examples for org.apache.curator.framework.CuratorFramework#getState()

The following examples show how to use org.apache.curator.framework.CuratorFramework#getState() . 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: ZKUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private static CuratorFramework getZookeeperClient(final String zkString, final RetryPolicy retryPolicy) {
    if (StringUtils.isEmpty(zkString)) {
        throw new IllegalArgumentException("ZOOKEEPER_QUORUM is empty!");
    }
    try {
        CuratorFramework instance = CACHE.get(zkString, new Callable<CuratorFramework>() {
            @Override
            public CuratorFramework call() throws Exception {
                return newZookeeperClient(zkString, retryPolicy);
            }
        });
        // during test, curator may be closed by others, remove it from CACHE and reinitialize a new one
        if (instance.getState() != CuratorFrameworkState.STARTED) {
            logger.warn("curator for {} is closed by others unexpectedly, reinitialize a new one", zkString);
            CACHE.invalidate(zkString);
            instance = getZookeeperClient(zkString, retryPolicy);
        }
        return instance;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: EventContainer.java    From DBus with Apache License 2.0 6 votes vote down vote up
/**
 * 在拉完全量后将此schema的kafka consumer的offset设置为最新
 *
 * @param dbSchema
 */
/*public void setKafkaOffsetToLargest(String targetTopic){
	if(targetTopic==null)
		return;
	TopicPartition partition0 = new TopicPartition(targetTopic, 0);
	KafkaConsumerContainer.getInstances().getConsumer(targetTopic).seekToEnd(Arrays.asList(partition0));
}*/
protected <T> T deserialize(String path, Class<T> clazz) throws Exception {
    T packet = null;
    CuratorFramework curator = CuratorContainer.getInstance().getCurator();
    if (curator.getState() == CuratorFrameworkState.STOPPED) {
        LOG.info("[EventContainer] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
    } else {
        byte[] bytes = curator.getData().forPath(path);
        if (bytes != null && bytes.length != 0) {
            packet = JsonUtil.fromJson(new String(bytes, Charset.forName("UTF-8")), clazz);
        }
    }
    return packet;
}
 
Example 3
Source File: Zk.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
/** Connect a curator client to a running ZooKepper server. */
public static void connect(CuratorFramework client) {
    switch(client.getState()) {
        case LATENT :
            client.start();
            try { client.blockUntilConnected(); }
            catch (InterruptedException ex) { throw new RuntimeException(ex); }
            return;
        case STARTED :
            //LOG.warn("CuratorFramework already started");
            return ;
        case STOPPED :
            throw new DeltaException("CuratorFramework closed");
        default :
            break;
    }
}
 
Example 4
Source File: ZKUtil.java    From kylin with Apache License 2.0 6 votes vote down vote up
private static CuratorFramework getZookeeperClient(final String zkString, final RetryPolicy retryPolicy) {
    if (StringUtils.isEmpty(zkString)) {
        throw new IllegalArgumentException("ZOOKEEPER_QUORUM is empty!");
    }
    try {
        CuratorFramework instance = CACHE.get(zkString, new Callable<CuratorFramework>() {
            @Override
            public CuratorFramework call() throws Exception {
                return newZookeeperClient(zkString, retryPolicy);
            }
        });
        // during test, curator may be closed by others, remove it from CACHE and reinitialize a new one
        if (instance.getState() != CuratorFrameworkState.STARTED) {
            logger.warn("curator for {} is closed by others unexpectedly, reinitialize a new one", zkString);
            CACHE.invalidate(zkString);
            instance = getZookeeperClient(zkString, retryPolicy);
        }
        return instance;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: AbstractEvent.java    From DBus with Apache License 2.0 5 votes vote down vote up
protected <T> T deserialize(String path, Class<T> clazz) throws Exception {
    T packet = null;
    CuratorFramework curator = CuratorContainer.getInstance().getCurator();
    if (curator.getState() == CuratorFrameworkState.STOPPED) {
        LOG.info("[control-event] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
    } else {
        byte[] bytes = curator.getData().forPath(path);
        if (bytes != null && bytes.length != 0) {
            packet = JsonUtil.fromJson(new String(bytes, Charset.forName("UTF-8")), clazz);
        }
    }
    return packet;
}
 
Example 6
Source File: AbstractEvent.java    From DBus with Apache License 2.0 5 votes vote down vote up
protected void saveZk(String node, String packet) {
    try {
        CuratorFramework curator = CuratorContainer.getInstance().getCurator();
        if (curator.getState() == CuratorFrameworkState.STOPPED) {
            LOG.info("[control-event] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
        } else {
            curator.setData().forPath(node, packet.getBytes());
        }
    } catch (Exception e) {
        LOG.error("[control-event] 报错znode: " + node + ",数据包:" + packet + "失败!", e);
    }
}
 
Example 7
Source File: ProjectCheckHeartBeatEvent.java    From DBus with Apache License 2.0 5 votes vote down vote up
/**
 * 根据根路径,获取所有末端叶子ZK节点
 *
 * @param basePath 根路径
 * @return
 * @throws Exception
 */
private Set<String> getZKNodePathsFromPath(String basePath, Set<String> result) {
    Set<String> defaultSet = new HashSet<>();
    try {
        CuratorFramework curator = CuratorContainer.getInstance().getCurator();
        if (curator.getState() == CuratorFrameworkState.STOPPED) {
            LOG.info("[traverse zk node paths] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
            return defaultSet;
        } else {
            //获取下一级path
            List<String> paths = curator.getChildren().forPath(basePath);
            if (paths.size() > 0) {
                //遍历添加下一级节点
                for (String path : paths) {
                    path = basePath + "/" + path;
                    getZKNodePathsFromPath(path, result);
                }
            } else {
                //如果是末端叶子节点,那么将完整的路径加入到结果集
                if (!HeartBeatConfigContainer.getInstance().getHbConf().getProjectMonitorPath()
                        .equals(basePath)) {// 默认的base path不加入
                    LOG.info("add nodePath : " + basePath);
                    result.add(basePath);
                }

            }
            return result;
        }
    } catch (Exception e) {
        LoggerFactory.getLogger().error("[ traverse zk node paths] path :" + basePath, e);
        return defaultSet;
    }
}
 
Example 8
Source File: EventContainer.java    From DBus with Apache License 2.0 5 votes vote down vote up
protected void saveZk(String node, String packet) {
    try {
        CuratorFramework curator = CuratorContainer.getInstance().getCurator();
        if (curator.getState() == CuratorFrameworkState.STOPPED) {
            LOG.info("[EventContainer] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
        } else {
            curator.setData().forPath(node, packet.getBytes());
        }
    } catch (Exception e) {
        LOG.error("[control-event] 报错znode: " + node + ",数据包:" + packet + "失败!", e);
    }
}
 
Example 9
Source File: ZookeeperWorkerRegister.java    From idworker with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭注册
 */
@Override
public synchronized void logout() {
    CuratorFramework client = (CuratorFramework) regCenter.getRawClient();
    if (client != null && client.getState() == CuratorFrameworkState.STARTED) {
        // 移除注册节点(最大程度的自动释放资源)
        regCenter.remove(nodePath.getWorkerIdPath());
        // 关闭连接
        regCenter.close();
    }
}
 
Example 10
Source File: MesosMasterHealthCheck.java    From myriad with Apache License 2.0 5 votes vote down vote up
@Override
protected Result check() throws Exception {
	String mesosMaster = cfg.getMesosMaster();
	int zkIndex = mesosMaster.indexOf("zk://", 0);
	if (zkIndex >= 0) {
		String zkHostPorts = mesosMaster.substring(5,
				mesosMaster.indexOf("/", 5));

		String[] hostPorts = zkHostPorts.split(",");

		for (String hostPort : hostPorts) {
			CuratorFramework client = CuratorFrameworkFactory.newClient(
					hostPort, new ExponentialBackoffRetry(1000, 3));
			client.start();
			client.blockUntilConnected(5, TimeUnit.SECONDS);

			switch (client.getState()) {
			case STARTED:
				return Result.healthy();
			case STOPPED:
				LOGGER.fine("Unable to reach: " + hostPort);
			case LATENT:
				LOGGER.fine("Unable to reach: " + hostPort);
			default:
				LOGGER.fine("Unable to reach: " + hostPort);
			}
		}
	} else {
		if (HealthCheckUtils.checkHostPort(mesosMaster)) {
			return Result.healthy();
		}
	}

	return Result.unhealthy("Unable to connect to: " + mesosMaster);
}
 
Example 11
Source File: CuratorManager.java    From snowizard-discovery with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Constructor
 * 
 * @param framework
 *            {@link CuratorFramework}
 */
public CuratorManager(final CuratorFramework framework) {
    this.framework = checkNotNull(framework);
    // start framework directly to allow other bundles to interact with zookeeper
    // during their run() method.
    if (framework.getState() != CuratorFrameworkState.STARTED) {
        framework.start();
    }
}
 
Example 12
Source File: MesosMasterHealthCheck.java    From incubator-myriad with Apache License 2.0 4 votes vote down vote up
@Override
protected Result check() throws Exception {
  String mesosMaster = cfg.getMesosMaster();
  int zkIndex = mesosMaster.indexOf("zk://", 0);
  Result result = Result.unhealthy("Unable to connect to: " + mesosMaster);
  if (zkIndex >= 0) {
    final int fromIndex = 5;
    String zkHostPorts = mesosMaster.substring(fromIndex, mesosMaster.indexOf("/", fromIndex));

    String[] hostPorts = zkHostPorts.split(",");

    for (String hostPort : hostPorts) {
      final int maxRetries = 3;
      final int baseSleepTimeMs = 1000;
      CuratorFramework client = CuratorFrameworkFactory.newClient(hostPort, new ExponentialBackoffRetry(baseSleepTimeMs,
          maxRetries));
      client.start();
      final int blockTime = 5;
      client.blockUntilConnected(blockTime, TimeUnit.SECONDS);

      switch (client.getState()) {
        case STARTED:
          result = Result.healthy();
          break;
        case STOPPED:
          LOGGER.info("Unable to reach: ", hostPort);
          break;
        case LATENT:
          LOGGER.info("Unable to reach: ", hostPort);
          break;
        default:
          LOGGER.info("Unable to reach: ", hostPort);
      }
    }
  } else {
    if (HealthCheckUtils.checkHostPort(mesosMaster)) {
      result = Result.healthy();
    }
  }

  return result;
}