Java Code Examples for org.apache.zookeeper.KeeperException#NodeExistsException

The following examples show how to use org.apache.zookeeper.KeeperException#NodeExistsException . 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: Scheduler.java    From workflow with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 2
Source File: LogSearchConfigLogFeederZK.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example 3
Source File: TenantRepository.java    From vespa with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
            }
        }
    }
}
 
Example 4
Source File: CdcrBufferStateManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 5
Source File: ZkRpcClientExecutor.java    From hasting with MIT License 6 votes vote down vote up
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);
	}
}
 
Example 6
Source File: ZooKeeperCuratorFailoverTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@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
  }
}
 
Example 7
Source File: ExclusiveJobWrapper.java    From nakadi with MIT License 6 votes vote down vote up
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);
}
 
Example 8
Source File: ZKDelegationTokenSecretManager.java    From big-c with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 9
Source File: ZookeeperConfigActivator.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 10
Source File: BaseClient.java    From opensharding-spi-impl with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: ZKDelegationTokenSecretManager.java    From hadoop with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 12
Source File: ServiceUnitZkUtils.java    From pulsar with Apache License 2.0 5 votes vote down vote up
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;
        }
    }
}
 
Example 13
Source File: DistributedAtomicValue.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: DistributedBarrier.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * 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
    }
}
 
Example 15
Source File: ZooKeeperStateHandleStore.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 16
Source File: ZKPlacementStateManager.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 17
Source File: ZooKeeperCommandExecutor.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private void createZkPathIfMissing(String zkPath) throws Exception {
    try {
        curator.create().forPath(zkPath);
    } catch (KeeperException.NodeExistsException ignored) {
        // Ignore.
    }
}
 
Example 18
Source File: DistributedDoubleBarrier.java    From xian with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 19
Source File: ZKSignerSecretProvider.java    From big-c with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 20
Source File: Curator4ZookeeperRegistry.java    From spring-cloud-sofastack-samples with Apache License 2.0 4 votes vote down vote up
/***
 * 注册 服务信息
 * @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);
    }
}