下面列出了org.apache.zookeeper.KeeperException#NodeExistsException ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates the tenants that should always be present into ZooKeeper. Will not fail if the node
* already exists, as this is OK and might happen when several config servers start at the
* same time and try to call this method.
*/
private synchronized void createSystemTenants(ConfigserverConfig configserverConfig) {
List<TenantName> systemTenants = new ArrayList<>();
systemTenants.add(DEFAULT_TENANT);
if (configserverConfig.hostedVespa()) systemTenants.add(HOSTED_VESPA_TENANT);
for (final TenantName tenantName : systemTenants) {
try {
writeTenantPath(tenantName);
} catch (RuntimeException e) {
// Do nothing if we get NodeExistsException
if (e.getCause().getClass() != KeeperException.NodeExistsException.class) {
throw e;
}
}
}
}
private void createStateNode() {
SolrZkClient zkClient = core.getCoreContainer().getZkController().getZkClient();
try {
if (!zkClient.exists(this.getZnodePath(), true)) {
if (!zkClient.exists(this.getZnodeBase(), true)) {
zkClient.makePath(this.getZnodeBase(), null, CreateMode.PERSISTENT, null, false, true); // Should be a no-op if node exists
}
zkClient.create(this.getZnodePath(), DEFAULT_STATE.getBytes(), CreateMode.PERSISTENT, true);
if (log.isInfoEnabled()) {
log.info("Created znode {}", this.getZnodePath());
}
}
} catch (KeeperException.NodeExistsException ne) {
// Someone got in first and created the node.
} catch (KeeperException | InterruptedException e) {
log.warn("Failed to create CDCR buffer state node", e);
}
}
@Test
public void verifyZooKeeperRecoversWithTwoPeersAlive() throws Exception {
zk.stopPeer(0);
zk.stopPeer(1);
zk.awaitDown(5, MINUTES);
zk.resetPeer(0);
zk.startPeer(0);
zk.awaitUp(5, MINUTES);
try {
zk.curatorWithSuperAuth().create().forPath(FOO, FOO_DATA);
assertArrayEquals(FOO_DATA, zk.curatorWithSuperAuth().getData().forPath(FOO));
} catch (KeeperException.NodeExistsException ignore) {
// ignored
}
}
private void doUploadServerInfo(RpcHostAndPort hostAndPort){
String serverKey = this.genServerKey(hostAndPort.getHost(),hostAndPort.getPort());
String hostAndPortJson = JSONUtils.toJSON(hostAndPort);
logger.info("create rpc provider:"+hostAndPortJson);
try{
byte[] data = hostAndPortJson.getBytes(defaultEncoding);
this.zkclient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(serverKey, data);
logger.info("add rpc provider success "+serverKey);
}catch(Exception e){
if(e instanceof KeeperException.NodeExistsException){
return;
}
logger.error("add provider error",e);
throw new RpcException(e);
}
}
private void createGlobalConfigNode(JsonArray globalConfigNode, String clusterName) {
String globalConfigNodePath = String.format("/%s/global", clusterName);
String data = InputConfigGson.gson.toJson(globalConfigNode);
try {
if (logFeederClusterCache.getCurrentData(globalConfigNodePath) != null) {
client.setData().forPath(globalConfigNodePath, data.getBytes());
} else {
client.create().creatingParentContainersIfNeeded().withACL(LogSearchConfigZKHelper.getAcls(properties)).forPath(globalConfigNodePath, data.getBytes());
}
} catch (Exception e) {
if (e instanceof KeeperException.NodeExistsException) {
logger.info("Node '{}' already exists. It won't be re-created.", globalConfigNodePath);
} else {
logger.warn("Exception during global config node creation/update", e);
}
}
}
private void queueTask(RunId runId, ExecutableTask task)
{
String path = ZooKeeperConstants.getStartedTaskPath(runId, task.getTaskId());
try
{
StartedTask startedTask = new StartedTask(workflowManager.getInstanceName(), LocalDateTime.now(Clock.systemUTC()), 0);
byte[] data = workflowManager.getSerializer().serialize(startedTask);
workflowManager.getCurator().create().creatingParentContainersIfNeeded().forPath(path, data);
Queue queue = queues.get(task.getTaskType());
queue.put(task);
log.info("Queued task: " + task);
}
catch ( KeeperException.NodeExistsException ignore )
{
log.debug("Task already queued: " + task);
// race due to caching latency - task already started
}
catch ( Exception e )
{
String message = "Could not start task " + task;
log.error(message, e);
throw new RuntimeException(e);
}
}
private void updateJobTimestamp() throws Exception {
try {
// try to create node for the case if it doesn't exist
zkHolder.get()
.create()
.creatingParentsIfNeeded()
.forPath(zkPath + "/latest");
} catch (final KeeperException.NodeExistsException e) {
// "latest" node may already exist - this is ok
}
// update the latest timestamp of job
final DateTime now = new DateTime(DateTimeZone.UTC);
final byte[] currentTimeAsBytes = objectMapper.writeValueAsString(now).getBytes(Charsets.UTF_8);
zkHolder.get()
.setData()
.forPath(zkPath + "/latest", currentTimeAsBytes);
}
/**
* Utility to set the barrier node
*
* @throws Exception errors
*/
public synchronized void setBarrier() throws Exception
{
try
{
client.create().creatingParentContainersIfNeeded().forPath(barrierPath);
}
catch ( KeeperException.NodeExistsException ignore )
{
// ignore
}
}
private void createZkPathIfMissing(String zkPath) throws Exception {
try {
curator.create().forPath(zkPath);
} catch (KeeperException.NodeExistsException ignored) {
// Ignore.
}
}
private void createServerLoadPathIfNoExists(byte[] data) throws KeeperException, IOException {
try {
Utils.zkCreateFullPathOptimistic(
zkClient, serverLoadPath, data, zkClient.getDefaultACL(), CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException nee) {
logger.debug("the server load path {} is already created by others", serverLoadPath, nee);
}
}
/**
* Gets a state handle from ZooKeeper and optionally locks it.
*
* @param pathInZooKeeper Path in ZooKeeper to get the state handle from
* @param lock True if we should lock the node; otherwise false
* @return The state handle
* @throws IOException Thrown if the method failed to deserialize the stored state handle
* @throws Exception Thrown if a ZooKeeper operation failed
*/
@SuppressWarnings("unchecked")
private RetrievableStateHandle<T> get(String pathInZooKeeper, boolean lock) throws Exception {
checkNotNull(pathInZooKeeper, "Path in ZooKeeper");
final String path = normalizePath(pathInZooKeeper);
if (lock) {
// try to lock the node
try {
client.create().withMode(CreateMode.EPHEMERAL).forPath(getLockPath(path));
} catch (KeeperException.NodeExistsException ignored) {
// we have already created the lock
}
}
boolean success = false;
try {
byte[] data = client.getData().forPath(path);
try {
RetrievableStateHandle<T> retrievableStateHandle = InstantiationUtil.deserializeObject(
data,
Thread.currentThread().getContextClassLoader());
success = true;
return retrievableStateHandle;
} catch (IOException | ClassNotFoundException e) {
throw new IOException("Failed to deserialize state handle from ZooKeeper data from " +
path + '.', e);
}
} finally {
if (!success && lock) {
// release the lock
release(path);
}
}
}
/**
* Atomic values are initially set to the equivalent of <code>NULL</code> in a database.
* Use this method to initialize the value. The value will be set if and only iff the node does not exist.
*
* @param value the initial value to set
* @return true if the value was set, false if the node already existed
* @throws Exception ZooKeeper errors
*/
public boolean initialize(byte[] value) throws Exception
{
try
{
client.create().creatingParentContainersIfNeeded().forPath(path, value);
}
catch ( KeeperException.NodeExistsException ignore )
{
// ignore
return false;
}
return true;
}
private static void createZnodeOptimistic(ZooKeeper zkc, String path, String data, CreateMode mode)
throws KeeperException, InterruptedException {
try {
// create node optimistically
checkNotNull(LocalZooKeeperConnectionService.createIfAbsent(zkc, path, data, mode));
} catch (NoNodeException e) {
// if path contains multiple levels after the root, create the intermediate nodes first
String[] parts = path.split("/");
if (parts.length > 3) {
String int_path = path.substring(0, path.lastIndexOf("/"));
if (zkc.exists(int_path, false) == null) {
// create the intermediate nodes
try {
ZkUtils.createFullPathOptimistic(zkc, int_path, new byte[0], Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException nee) {
LOG.debug(
"Other broker preempted the full intermediate path [{}] already. Continue for acquiring the leaf ephemeral node.",
int_path);
}
}
checkNotNull(LocalZooKeeperConnectionService.createIfAbsent(zkc, path, data, mode));
} else {
// If failed to create immediate child of root node, throw exception
throw e;
}
}
}
private void createPersistentNode(String nodePath) throws Exception {
try {
zkClient.create().withMode(CreateMode.PERSISTENT).forPath(nodePath);
} catch (KeeperException.NodeExistsException ne) {
LOG.debug(nodePath + " znode already exists !!");
} catch (Exception e) {
throw new IOException(nodePath + " znode could not be created !!", e);
}
}
protected final void deleteNamespace() throws KeeperException, InterruptedException {
try {
holder.getZooKeeper().delete(rootNode, ZookeeperConstants.VERSION);
} catch (final KeeperException.NodeExistsException | KeeperException.NotEmptyException ex) {
log.info("delete root :{}", ex.getMessage());
}
rootExist = false;
}
protected void registryResource(String path, CreateMode createMode) {
try {
LOGGER.info("Registry context path: {} with mode: {}.", path, createMode);
zkClient.create().creatingParentContainersIfNeeded().withMode(createMode).forPath(path);
} catch (KeeperException.NodeExistsException nodeExistsException) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Context path has exists in zookeeper, path=" + path);
}
} catch (Exception e) {
throw new ArkRuntimeException("Failed to register resource to zookeeper registry!", e);
}
}
private void createPersistentNode(String nodePath) throws Exception {
try {
zkClient.create().withMode(CreateMode.PERSISTENT).forPath(nodePath);
} catch (KeeperException.NodeExistsException ne) {
LOG.debug(nodePath + " znode already exists !!");
} catch (Exception e) {
throw new IOException(nodePath + " znode could not be created !!", e);
}
}
/***
* 注册 服务信息
* @param config
* @return
* @throws Exception
*/
protected void registerProviderUrls(ProviderConfig config) {
String appName = config.getAppName();
// 注册服务端节点
try {
// 避免重复计算
List<String> urls;
if (providerUrls.containsKey(config)) {
urls = providerUrls.get(config);
} else {
urls = ZookeeperRegistryHelper.convertProviderToUrls(config);
providerUrls.put(config, urls);
}
if (CommonUtils.isNotEmpty(urls)) {
String providerPath = buildProviderPath(rootPath, config);
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName,
LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB_START, providerPath));
}
for (String url : urls) {
url = URLEncoder.encode(url, "UTF-8");
String providerUrl = providerPath + CONTEXT_SEP + url;
try {
getAndCheckZkClient()
.create()
.creatingParentContainersIfNeeded()
.withMode(ephemeralNode ? CreateMode.EPHEMERAL : CreateMode.PERSISTENT)
// 是否永久节点
.forPath(providerUrl,
config.isDynamic() ? PROVIDER_ONLINE : PROVIDER_OFFLINE);
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName,
LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB, providerUrl));
}
} catch (KeeperException.NodeExistsException nodeExistsException) {
if (LOGGER.isWarnEnabled(appName)) {
LOGGER.warnWithApp(appName,
"provider has exists in zookeeper, provider=" + providerUrl);
}
}
}
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName,
LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB_OVER, providerPath));
}
}
} catch (Throwable t) {
throw new SofaRpcRuntimeException("Failed to register provider to zookeeperRegistry!",
t);
}
}
@Override
public void init(Properties config, ServletContext servletContext,
long tokenValidity) throws Exception {
Object curatorClientObj = servletContext.getAttribute(
ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE);
if (curatorClientObj != null
&& curatorClientObj instanceof CuratorFramework) {
client = (CuratorFramework) curatorClientObj;
} else {
client = createCuratorClient(config);
servletContext.setAttribute(
ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE, client);
}
this.tokenValidity = tokenValidity;
shouldDisconnect = Boolean.parseBoolean(
config.getProperty(DISCONNECT_FROM_ZOOKEEPER_ON_SHUTDOWN, "true"));
path = config.getProperty(ZOOKEEPER_PATH);
if (path == null) {
throw new IllegalArgumentException(ZOOKEEPER_PATH
+ " must be specified");
}
try {
nextRolloverDate = System.currentTimeMillis() + tokenValidity;
// everyone tries to do this, only one will succeed and only when the
// znode doesn't already exist. Everyone else will synchronize on the
// data from the znode
client.create().creatingParentsIfNeeded()
.forPath(path, generateZKData(generateRandomSecret(),
generateRandomSecret(), null));
zkVersion = 0;
LOG.info("Creating secret znode");
} catch (KeeperException.NodeExistsException nee) {
LOG.info("The secret znode already exists, retrieving data");
}
// Synchronize on the data from the znode
// passing true tells it to parse out all the data for initing
pullFromZK(true);
long initialDelay = nextRolloverDate - System.currentTimeMillis();
// If it's in the past, try to find the next interval that we should
// be using
if (initialDelay < 1l) {
int i = 1;
while (initialDelay < 1l) {
initialDelay = nextRolloverDate + tokenValidity * i
- System.currentTimeMillis();
i++;
}
}
super.startScheduler(initialDelay, tokenValidity);
}
private synchronized boolean internalEnter(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception
{
boolean result = true;
do
{
List<String> children = getChildrenForEntering();
int count = (children != null) ? children.size() : 0;
if ( count >= memberQty )
{
try
{
client.create().forPath(readyPath);
}
catch ( KeeperException.NodeExistsException ignore )
{
// ignore
}
break;
}
if ( hasMaxWait && !hasBeenNotified.get() )
{
long elapsed = System.currentTimeMillis() - startMs;
long thisWaitMs = maxWaitMs - elapsed;
if ( thisWaitMs <= 0 )
{
result = false;
}
else
{
wait(thisWaitMs);
}
if ( !hasBeenNotified.get() )
{
result = false;
}
}
else
{
wait();
}
} while ( false );
return result;
}