Java Code Examples for org.apache.zookeeper.CreateMode#EPHEMERAL_SEQUENTIAL

The following examples show how to use org.apache.zookeeper.CreateMode#EPHEMERAL_SEQUENTIAL . 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: FailureRetryZKClient.java    From twill with Apache License 2.0 6 votes vote down vote up
@Override
public OperationFuture<String> create(final String path, @Nullable final byte[] data, final CreateMode createMode,
                                      final boolean createParent, final Iterable<ACL> acl) {
  // No retry for any SEQUENTIAL node, as some algorithms depends on only one sequential node being created.
  if (createMode == CreateMode.PERSISTENT_SEQUENTIAL || createMode == CreateMode.EPHEMERAL_SEQUENTIAL) {
    return super.create(path, data, createMode, createParent, acl);
  }

  final SettableOperationFuture<String> result = SettableOperationFuture.create(path, Threads.SAME_THREAD_EXECUTOR);
  Futures.addCallback(super.create(path, data, createMode, createParent, acl),
                      new OperationFutureCallback<String>(OperationType.CREATE, System.currentTimeMillis(),
                                                          path, result, new Supplier<OperationFuture<String>>() {
                        @Override
                        public OperationFuture<String> get() {
                          return FailureRetryZKClient.super.create(path, data, createMode, createParent, acl);
                        }
                      }));
  return result;
}
 
Example 2
Source File: SimDistribStateManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private Node createNode(Node parentNode, CreateMode mode, StringBuilder fullChildPath, String baseChildName, byte[] data, boolean attachToParent) throws IOException {
  String nodeName = baseChildName;
  if ((parentNode.mode == CreateMode.EPHEMERAL || parentNode.mode == CreateMode.EPHEMERAL_SEQUENTIAL) &&
      (mode == CreateMode.EPHEMERAL || mode == CreateMode.EPHEMERAL_SEQUENTIAL)) {
    throw new IOException("NoChildrenEphemerals for " + parentNode.path);
  }
  if (CreateMode.PERSISTENT_SEQUENTIAL == mode || CreateMode.EPHEMERAL_SEQUENTIAL == mode) {
    nodeName = nodeName + String.format(Locale.ROOT, "%010d", parentNode.seq);
    parentNode.seq++;
  }

  fullChildPath.append(nodeName);
  String owner = mode == CreateMode.EPHEMERAL || mode == CreateMode.EPHEMERAL_SEQUENTIAL ? id : "0";
  Node child = new Node(parentNode, nodeName, fullChildPath.toString(), data, mode, owner);

  if (attachToParent) {
    parentNode.setChild(nodeName, child);
  }
  return child;
}
 
Example 3
Source File: ServiceDiscoveryImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected void internalRegisterService(ServiceInstance<T> service) throws Exception
{
    byte[] bytes = serializer.serialize(service);
    String path = pathForInstance(service.getName(), service.getId());

    final int MAX_TRIES = 2;
    boolean isDone = false;
    for ( int i = 0; !isDone && (i < MAX_TRIES); ++i )
    {
        try
        {
CreateMode mode;
switch (service.getServiceType()) {
case DYNAMIC:
	mode = CreateMode.EPHEMERAL;
	break;
case DYNAMIC_SEQUENTIAL:
	mode = CreateMode.EPHEMERAL_SEQUENTIAL;
	break;
default:
	mode = CreateMode.PERSISTENT;
	break;
}
            client.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, bytes);
client.setData().forPath(pathForName(service.getName()), serviceDefinitionSerializer.serialize(service.getPayload()));
            isDone = true;
        }
        catch ( KeeperException.NodeExistsException e )
        {
            client.delete().forPath(path);  // must delete then re-create so that watchers fire
        }
    }
}
 
Example 4
Source File: SimDistribStateManager.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void removeEphemeralChildren(String id) throws NoSuchElementException, BadVersionException, IOException {
  Set<String> kids = new HashSet<>(children.keySet());
  for (String kid : kids) {
    Node n = children.get(kid);
    if (n == null) {
      continue;
    }
    if ((CreateMode.EPHEMERAL == n.mode || CreateMode.EPHEMERAL_SEQUENTIAL == n.mode) &&
        id.equals(n.owner)) {
      removeChild(n.name, -1);
    } else {
      n.removeEphemeralChildren(id);
    }
  }
}
 
Example 5
Source File: TestPersistentNode.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testEphemeralSequentialWithProtectionReconnection() throws Exception
{
    Timing timing = new Timing();
    PersistentNode pen = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/test/one");

        pen = new PersistentNode(client, CreateMode.EPHEMERAL_SEQUENTIAL, true, "/test/one/two", new byte[0]);
        pen.start();
        List<String> children = client.getChildren().forPath("/test/one");
        System.out.println("children before restart: "+children);
        Assert.assertEquals(1, children.size());
        server.stop();
        timing.sleepABit();
        server.restart();
        timing.sleepABit();
        List<String> childrenAfter = client.getChildren().forPath("/test/one");
        System.out.println("children after restart: "+childrenAfter);
        Assert.assertEquals(children, childrenAfter, "unexpected znodes: "+childrenAfter);
    }
    finally
    {
        CloseableUtils.closeQuietly(pen);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 6
Source File: ServiceDiscoveryImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected void internalRegisterService(ServiceInstance<T> service) throws Exception
{
    byte[] bytes = serializer.serialize(service);
    String path = pathForInstance(service.getName(), service.getId());

    final int MAX_TRIES = 2;
    boolean isDone = false;
    for ( int i = 0; !isDone && (i < MAX_TRIES); ++i )
    {
        try
        {
CreateMode mode;
switch (service.getServiceType()) {
case DYNAMIC:
	mode = CreateMode.EPHEMERAL;
	break;
case DYNAMIC_SEQUENTIAL:
	mode = CreateMode.EPHEMERAL_SEQUENTIAL;
	break;
default:
	mode = CreateMode.PERSISTENT;
	break;
}
            client.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, bytes);
            isDone = true;
        }
        catch ( KeeperException.NodeExistsException e )
        {
            client.delete().forPath(path);  // must delete then re-create so that watchers fire
        }
    }
}
 
Example 7
Source File: AccessOption.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to get zookeeper create mode from options
 * @param options bitmask representing mode; least significant set flag is selected
 * @return zookeeper create mode
 */
public static CreateMode getMode(int options) {
  if ((options & PERSISTENT) > 0) {
    return CreateMode.PERSISTENT;
  } else if ((options & EPHEMERAL) > 0) {
    return CreateMode.EPHEMERAL;
  } else if ((options & PERSISTENT_SEQUENTIAL) > 0) {
    return CreateMode.PERSISTENT_SEQUENTIAL;
  } else if ((options & EPHEMERAL_SEQUENTIAL) > 0) {
    return CreateMode.EPHEMERAL_SEQUENTIAL;
  }

  return null;
}
 
Example 8
Source File: CuratorSingletonService.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
void advertise(
    Closer closer,
    InetSocketAddress endpoint,
    Map<String, InetSocketAddress> additionalEndpoints)
    throws AdvertiseException, InterruptedException {

  byte[] nodeData = serializeAdvertisement(endpoint, additionalEndpoints);
  PersistentNode persistentNode =
      new PersistentNode(
          client,
          CreateMode.EPHEMERAL_SEQUENTIAL,

          // TODO(John Sirois): Enable GUID protection once clients are updated to support
          // its effects on group member node naming.  We get nodes like:
          //   4f5f98c4-8e71-41e3-8c8d-1c9a1f5f5df9-member_000000001
          // Clients expect member_ is the prefix and are not prepared for the GUID.
          false /* GUID protection */,

          ZKPaths.makePath(groupPath, memberToken),
          nodeData);
  persistentNode.start();
  closer.register(persistentNode);

  // NB: This blocks on initial server set node population to emulate legacy
  // SingletonService.LeaderControl.advertise (Group.join) behavior. Asynchronous
  // population is an option though, we simply need to remove this wait.
  if (!persistentNode.waitForInitialCreate(Long.MAX_VALUE, TimeUnit.DAYS)) {
    throw new AdvertiseException("Timed out waiting for leader advertisement.");
  }
}
 
Example 9
Source File: PartitionManager.java    From fluo with Apache License 2.0 5 votes vote down vote up
PartitionManager(Environment env, long minSleepTime, long maxSleepTime) {
  try {
    this.curator = env.getSharedResources().getCurator();
    this.env = env;

    this.minSleepTime = minSleepTime;
    this.maxSleepTime = maxSleepTime;
    this.retrySleepTime = minSleepTime;

    groupSize = env.getConfiguration().getInt(FluoConfigurationImpl.WORKER_PARTITION_GROUP_SIZE,
        FluoConfigurationImpl.WORKER_PARTITION_GROUP_SIZE_DEFAULT);

    myESNode = new PersistentNode(curator, CreateMode.EPHEMERAL_SEQUENTIAL, false,
        ZookeeperPath.FINDERS + "/" + ZK_FINDER_PREFIX, ("" + groupSize).getBytes(UTF_8));
    myESNode.start();
    myESNode.waitForInitialCreate(1, TimeUnit.MINUTES);

    childrenCache = new PathChildrenCache(curator, ZookeeperPath.FINDERS, true);
    childrenCache.getListenable().addListener(new FindersListener());
    childrenCache.start(StartMode.BUILD_INITIAL_CACHE);

    schedExecutor = Executors.newScheduledThreadPool(1,
        new FluoThreadFactory("Fluo worker partition manager"));
    schedExecutor.scheduleWithFixedDelay(new CheckTabletsTask(), 0, maxSleepTime,
        TimeUnit.MILLISECONDS);

    scheduleUpdate();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 10
Source File: RegistryImpl.java    From Scribengin with GNU Affero General Public License v3.0 5 votes vote down vote up
static CreateMode toCreateMode(NodeCreateMode mode) {
  if(mode == NodeCreateMode.PERSISTENT) return CreateMode.PERSISTENT ;
  else if(mode == NodeCreateMode.PERSISTENT_SEQUENTIAL) return CreateMode.PERSISTENT_SEQUENTIAL ;
  else if(mode == NodeCreateMode.EPHEMERAL) return CreateMode.EPHEMERAL ;
  else if(mode == NodeCreateMode.EPHEMERAL_SEQUENTIAL) return CreateMode.EPHEMERAL_SEQUENTIAL ;
  throw new RuntimeException("Mode " + mode + " is not supported") ;
}
 
Example 11
Source File: PersistentEphemeralNode.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
protected CreateMode getCreateMode(boolean pathIsSet)
{
    return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL;
}
 
Example 12
Source File: PersistentEphemeralNode.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
protected CreateMode getCreateMode(boolean pathIsSet)
{
    return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL;
}
 
Example 13
Source File: PersistentEphemeralNode.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
protected CreateMode getCreateMode(boolean pathIsSet)
{
    return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL;
}
 
Example 14
Source File: PersistentEphemeralNode.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
protected CreateMode getCreateMode(boolean pathIsSet)
{
    return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL;
}
 
Example 15
Source File: ZkClient.java    From helix with Apache License 2.0 4 votes vote down vote up
private boolean isSessionAwareOperation(String expectedSessionId, CreateMode mode) {
  return expectedSessionId != null && !expectedSessionId.isEmpty() && (
      mode == CreateMode.EPHEMERAL || mode == CreateMode.EPHEMERAL_SEQUENTIAL);
}