Java Code Examples for org.apache.curator.utils.ZKPaths#makePath()

The following examples show how to use org.apache.curator.utils.ZKPaths#makePath() . 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: TreeCacheExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
private static void setValue(CuratorFramework client, String command, String[] args) throws Exception {
	if (args.length != 2) {
		System.err.println("syntax error (expected set <path> <value>): " + command);
		return;
	}
	String name = args[0];
	if (name.contains("/")) {
		System.err.println("Invalid node name" + name);
		return;
	}
	String path = ZKPaths.makePath(PATH, name);
	byte[] bytes = args[1].getBytes();
	try {
		client.setData().forPath(path, bytes);
	} catch (KeeperException.NoNodeException e) {
		client.create().creatingParentsIfNeeded().forPath(path, bytes);
	}
}
 
Example 2
Source File: ZookeeperClusterDataManager.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public boolean registerWebCluster(String zNodeName, byte[] contents) {
    String zNodeFullPath = ZKPaths.makePath(ZookeeperConstants.PINPOINT_WEB_CLUSTER_PATH, zNodeName);

    logger.info("registerWebCluster() started. create UniqPath={}.", zNodeFullPath);
    CreateNodeMessage createNodeMessage = new CreateNodeMessage(zNodeFullPath, contents);
    PushWebClusterJob job = new PushWebClusterJob(createNodeMessage, retryInterval);
    if (!this.job.compareAndSet(null, job)) {
        logger.warn("Already Register Web Cluster Node.");
        return false;
    }

    // successful even for scheduler registration completion
    if (!isConnected()) {
        logger.info("Zookeeper is Disconnected.");
        return true;
    }

    if (!clusterDataManagerHelper.pushZnode(client, job.getCreateNodeMessage())) {
        timer.newTimeout(job, job.getRetryInterval(), TimeUnit.MILLISECONDS);
    }

    return true;
}
 
Example 3
Source File: ZKStream.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
CompletableFuture<VersionedMetadata<Long>> getMarkerData(long segmentId) {
    final CompletableFuture<VersionedMetadata<Long>> result = new CompletableFuture<>();
    final String path = ZKPaths.makePath(markerPath, String.format("%d", segmentId));
    store.getData(path, x -> BitConverter.readLong(x, 0))
         .whenComplete((res, ex) -> {
             if (ex != null) {
                 Throwable cause = Exceptions.unwrap(ex);
                 if (cause instanceof StoreException.DataNotFoundException) {
                     result.complete(null);
                 } else {
                     result.completeExceptionally(cause);
                 }
             } else {
                 result.complete(res);
             }
         });

    return result;
}
 
Example 4
Source File: FlinkServerRegister.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public FlinkServerRegister(FlinkConfiguration flinkConfiguration, String pinpointFlinkClusterPath) {
    Objects.requireNonNull(flinkConfiguration, "flinkConfiguration");
    this.clusterEnable = flinkConfiguration.isFlinkClusterEnable();
    this.connectAddress = flinkConfiguration.getFlinkClusterZookeeperAddress();
    this.sessionTimeout = flinkConfiguration.getFlinkClusterSessionTimeout();

    String zNodeName = getRepresentationLocalV4Ip() + ":" +  flinkConfiguration.getFlinkClusterTcpPort();
    if (StringUtils.isEmpty(pinpointFlinkClusterPath)) {
        throw new IllegalArgumentException("pinpointFlinkClusterPath must not be empty");
    }
    String zNodeFullPath = ZKPaths.makePath(pinpointFlinkClusterPath, zNodeName);

    CreateNodeMessage createNodeMessage = new CreateNodeMessage(zNodeFullPath, new byte[0]);
    int retryInterval = flinkConfiguration.getFlinkRetryInterval();
    this.pushFlinkNodeJob = new PushFlinkNodeJob(createNodeMessage, retryInterval);
}
 
Example 5
Source File: ZookeeperStreamMetadataStore.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void saveSourceCheckpoint(String cubeName, String segmentName, int rsID, String sourceCheckpoint) {
    checkPath(cubeName, segmentName);
    logger.trace("Save remote checkpoint {} {} {} with content {}.", cubeName, segmentName, rsID, sourceCheckpoint);
    try {
        String path = ZKPaths.makePath(cubeRoot, cubeName, CUBE_SRC_CHECKPOINT, segmentName,
                String.valueOf(rsID));
        if (client.checkExists().forPath(path) == null) {
            client.create().creatingParentsIfNeeded().forPath(path);
        } else {
            logger.warn("Checkpoint path already existed under path {}, overwrite with new one.", path);
        }
        client.setData().forPath(path, Bytes.toBytes(sourceCheckpoint));
        writeSuccess.getAndIncrement();
    } catch (Exception e) {
        writeFail.getAndIncrement();
        logger.error("Error when save remote checkpoint for " + cubeName + " " + segmentName , e);
        throw new StoreException(e);
    }
}
 
Example 6
Source File: CreateBuilderImpl.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to find the znode that matches the given path and protected id
 *
 * @param children    a list of candidates znodes
 * @param path        the path
 * @param protectedId the protected id
 * @return the absolute path of the znode or <code>null</code> if it is not found
 */
static String findNode(final List<String> children, final String path, final String protectedId)
{
    final String protectedPrefix = getProtectedPrefix(protectedId);
    String foundNode = Iterables.find
        (
            children,
            new Predicate<String>()
            {
                @Override
                public boolean apply(String node)
                {
                    return node.startsWith(protectedPrefix);
                }
            },
            null
        );
    if ( foundNode != null )
    {
        foundNode = ZKPaths.makePath(path, foundNode);
    }
    return foundNode;
}
 
Example 7
Source File: PathCacheExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
private static void setValue(CuratorFramework client, String command, String[] args) throws Exception {
	if (args.length != 2) {
		System.err.println("syntax error (expected set <path> <value>): " + command);
		return;
	}
	String name = args[0];
	if (name.contains("/")) {
		System.err.println("Invalid node name" + name);
		return;
	}
	String path = ZKPaths.makePath(PATH, name);
	byte[] bytes = args[1].getBytes();
	try {
		client.setData().forPath(path, bytes);
	} catch (KeeperException.NoNodeException e) {
		client.create().creatingParentsIfNeeded().forPath(path, bytes);
	}
}
 
Example 8
Source File: AsyncWrappers.java    From curator with Apache License 2.0 5 votes vote down vote up
private static CompletionStage<Void> ensure(AsyncCuratorFramework client, String path, ExistsOption option)
{
    String localPath = ZKPaths.makePath(path, "foo");
    return client
        .checkExists()
        .withOptions(Collections.singleton(option))
        .forPath(localPath)
        .thenApply(__ -> null)
        ;
}
 
Example 9
Source File: LeaderEventEngineTest.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void setMetaServers(List<Pair<String, HostPort>> servers) throws Exception {
	deleteChildren(ZKPathUtils.getMetaServersZkPath(), false);
	for (Pair<String, HostPort> pair : servers) {
		String path = ZKPaths.makePath(ZKPathUtils.getMetaServersZkPath(), pair.getKey());
		ensurePath(path);
		m_curator.setData().forPath(path, ZKSerializeUtils.serialize(pair.getValue()));
	}
}
 
Example 10
Source File: ZKUtils.java    From kafka-graphs with Apache License 2.0 5 votes vote down vote up
public static void addChild(CuratorFramework curator, String rootPath,
                            String child, CreateMode createMode, byte[] data) throws Exception {
    String path = ZKPaths.makePath(rootPath, child);
    try {
        log.debug("adding child {}", path);
        curator.create().creatingParentContainersIfNeeded().withMode(createMode).forPath(path, data);
    } catch (KeeperException.NodeExistsException e) {
        if (data.length != 0) {
            log.warn("could not add child {}", path);
        }
    }
}
 
Example 11
Source File: ZKUtils.java    From kafka-graphs with Apache License 2.0 5 votes vote down vote up
public static void removeChild(CuratorFramework curator, String rootPath,
                               String child) throws Exception {
    String path = ZKPaths.makePath(rootPath, child);
    try {
        log.debug("removing child {}", path);
        curator.delete().guaranteed().forPath(path);
    } catch (KeeperException.NoNodeException e) {
        // ignore
    }
}
 
Example 12
Source File: TaskManager.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private String getLastActiveTaskStatusPath(SingularityTaskId taskId) {
  return ZKPaths.makePath(
    LAST_ACTIVE_TASK_STATUSES_PATH_ROOT,
    taskId.getRequestId(),
    taskId.getId()
  );
}
 
Example 13
Source File: ZookeeperStreamMetadataStore.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public void updateSegmentBuildState(String cubeName, String segmentName, SegmentBuildState.BuildState state) {
    logger.trace("Update {} {} to state {}", cubeName, segmentName, state);
    checkPath(cubeName, segmentName);
    try {
        String stateStr = JsonUtil.writeValueAsString(state);
        String path = ZKPaths.makePath(cubeRoot, cubeName, CUBE_BUILD_STATE, segmentName);
        client.setData().forPath(path, Bytes.toBytes(stateStr));
        writeSuccess.getAndIncrement();
    } catch (Exception e) {
        writeFail.getAndIncrement();
        logger.error("Fail to update segment build state for " + segmentName + " to " + state, e);
        throw new StoreException(e);
    }
}
 
Example 14
Source File: ZookeeperConfigProvider.java    From exhibitor with Apache License 2.0 5 votes vote down vote up
/**
 * @param client curator instance for connecting to the config ensemble
 * @param baseZPath the base path for config nodes
 * @param defaults default properties
 * @param hostname this JVM's hostname
 * @throws Exception errors
 */
public ZookeeperConfigProvider(CuratorFramework client, String baseZPath, Properties defaults, String hostname) throws Exception
{
    this.client = client;
    this.defaults = defaults;
    this.hostname = hostname;
    configPath = ZKPaths.makePath(baseZPath, CONFIG_PATH);
    lockPath = ZKPaths.makePath(baseZPath, LOCK_PATH);
    cache = new PathChildrenCache(client, configPath, true);
}
 
Example 15
Source File: NamespaceImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
String    unfixForNamespace(String path)
{
    if ( (namespace != null) && (path != null) )
    {
        String      namespacePath = ZKPaths.makePath(namespace, null);
        if ( !namespacePath.equals("/") && path.startsWith(namespacePath) )
        {
            path = (path.length() > namespacePath.length()) ? path.substring(namespacePath.length()) : "/";
        }
    }
    return path;
}
 
Example 16
Source File: WebhookManager.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public void deleteCrashLoopUpdateForRetry(CrashLoopInfo crashLoopUpdate) {
  String updatePath = ZKPaths.makePath(
    SNS_CRASH_LOOP_RETRY,
    getCrashLoopUpdateId(crashLoopUpdate)
  );
  delete(updatePath);
}
 
Example 17
Source File: TaskManager.java    From Singularity with Apache License 2.0 4 votes vote down vote up
private String getDirectoryPath(SingularityTaskId taskId) {
  return ZKPaths.makePath(getHistoryPath(taskId), DIRECTORY_KEY);
}
 
Example 18
Source File: SimpleDistributedQueue.java    From curator with Apache License 2.0 4 votes vote down vote up
private byte[] internalElement(boolean removeIt, Watcher watcher) throws Exception
{
    ensurePath();

    List<String> nodes;
    try
    {
        nodes = (watcher != null) ? client.getChildren().usingWatcher(watcher).forPath(path) : client.getChildren().forPath(path);
    }
    catch ( KeeperException.NoNodeException dummy )
    {
        throw new NoSuchElementException();
    }
    Collections.sort(nodes);

    for ( String node : nodes )
    {
        if ( !node.startsWith(PREFIX) )
        {
            log.warn("Foreign node in queue path: " + node);
            continue;
        }

        String  thisPath = ZKPaths.makePath(path, node);
        try
        {
            byte[] bytes = client.getData().forPath(thisPath);
            if ( removeIt )
            {
                client.delete().forPath(thisPath);
            }
            return bytes;
        }
        catch ( KeeperException.NoNodeException ignore )
        {
            //Another client removed the node first, try next
        }
    }

    return null;
}
 
Example 19
Source File: Zk.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
/** Create the string for a path from the root, with first child and optional more children */
public static String zkPath(String root, String c, String...components) {
    return ZKPaths.makePath(root, c, components);
}
 
Example 20
Source File: DeployManager.java    From Singularity with Apache License 2.0 4 votes vote down vote up
private String getRequestDeployPath(String requestId) {
  return ZKPaths.makePath(BY_REQUEST_ROOT, requestId);
}