org.apache.curator.framework.api.transaction.CuratorOp Java Examples

The following examples show how to use org.apache.curator.framework.api.transaction.CuratorOp. 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: TransactionExamples.java    From curator with Apache License 2.0 6 votes vote down vote up
public static Collection<CuratorTransactionResult>      transaction(CuratorFramework client) throws Exception
{
    // this example shows how to use ZooKeeper's transactions

    CuratorOp createOp = client.transactionOp().create().forPath("/a/path", "some data".getBytes());
    CuratorOp setDataOp = client.transactionOp().setData().forPath("/another/path", "other data".getBytes());
    CuratorOp deleteOp = client.transactionOp().delete().forPath("/yet/another/path");

    Collection<CuratorTransactionResult>    results = client.transaction().forOperations(createOp, setDataOp, deleteOp);

    for ( CuratorTransactionResult result : results )
    {
        System.out.println(result.getForPath() + " - " + result.getType());
    }

    return results;
}
 
Example #2
Source File: CuratorPersister.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Updates and returns a transaction which can be used to delete the children of the provided
 * path, if any.
 */
private static void deleteChildrenOf(
    CuratorFramework client,
    String path,
    List<CuratorOp> operations,
    Set<String> pendingDeletePaths) throws Exception
{
  if (pendingDeletePaths.contains(path)) {
    // Short-circuit: Path and any children are already scheduled for deletion
    return;
  }
  // For each child: recurse into child (to delete any grandchildren, etc..), THEN delete child
  // itself
  for (String child : client.getChildren().forPath(path)) {
    String childPath = PersisterUtils.joinPaths(path, child);
    deleteChildrenOf(client, childPath, operations, pendingDeletePaths);
    if (!pendingDeletePaths.contains(childPath)) {
      // Avoid attempting to delete a path twice in the same transaction, just in case we're told
      // to delete two nodes where one is the child of the other (or something to that effect)
      operations.add(client.transactionOp().delete().forPath(childPath));
      pendingDeletePaths.add(childPath);
    }
  }
}
 
Example #3
Source File: CuratorPersister.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
public List<CuratorOp> build(
    CuratorFramework client,
    String serviceRootPath
) throws Exception
{
  // List of paths that are known to exist, or which are about to be created by the transaction
  // Includes "known to exist" in order to avoid repeated lookups for the same path
  Set<String> existingAndPendingCreatePaths = new HashSet<>();
  List<CuratorOp> operations = new ArrayList<>();
  operations.add(client.transactionOp().check().forPath(serviceRootPath));
  for (Map.Entry<String, byte[]> entry : pathBytesMap.entrySet()) {
    String path = entry.getKey();
    if (!existingAndPendingCreatePaths.contains(path)
        && client.checkExists().forPath(path) == null)
    {
      // Path does not exist and is not being created: Create value (and any parents as needed).
      operations.addAll(createParentsOf(client, path, existingAndPendingCreatePaths));
      operations.add(client.transactionOp().create().forPath(path, entry.getValue()));
      existingAndPendingCreatePaths.add(path);
    } else {
      // Path exists (or will exist): Update existing value.
      operations.add(client.transactionOp().setData().forPath(path, entry.getValue()));
    }
  }
  return operations;
}
 
Example #4
Source File: CuratorPersister.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
public List<CuratorOp> build(
    CuratorFramework client,
    String serviceRootPath
) throws Exception
{
  List<CuratorOp> operations = new ArrayList<>();
  // List of paths which are about to be deleted by the transaction
  Set<String> pendingDeletePaths = new HashSet<>();
  operations.add(client.transactionOp().check().forPath(serviceRootPath));
  for (String path : pathsToClear) {
    // if present, delete path and any children (unless already being deleted)
    if (!pendingDeletePaths.contains(path)
        && client.checkExists().forPath(path) != null)
    {
      deleteChildrenOf(client, path, operations, pendingDeletePaths);
      operations.add(client.transactionOp().delete().forPath(path));
      pendingDeletePaths.add(path);
    }
  }
  return operations;
}
 
Example #5
Source File: TestCompressionInTransactionNew.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetData() throws Exception
{
    final String path = "/a";
    final byte[]            data = "here's a string".getBytes();

    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();

        //Create uncompressed data in a transaction
        CuratorOp op = client.transactionOp().create().forPath(path, data);
        client.transaction().forOperations(op);
        Assert.assertEquals(data, client.getData().forPath(path));

        //Create compressed data in transaction
        op = client.transactionOp().setData().compressed().forPath(path, data);
        client.transaction().forOperations(op);
        Assert.assertEquals(data, client.getData().decompressed().forPath(path));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #6
Source File: MigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
private byte[] hash(List<CuratorOp> operations)
{
    MessageDigest digest;
    try
    {
        digest = MessageDigest.getInstance("SHA-256");
    }
    catch ( NoSuchAlgorithmException e )
    {
        throw new RuntimeException(e);
    }
    operations.forEach(op -> {
        if ( op instanceof ExtractingCuratorOp )
        {
            ((ExtractingCuratorOp)op).addToDigest(digest);
        }
        else
        {
            digest.update(op.toString().getBytes());
        }
    });
    return digest.digest();
}
 
Example #7
Source File: MigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
private CompletionStage<Void> applyMetaDataAfterEnsure(List<Migration> toBeApplied, String thisMetaDataPath)
{
    if ( debugCount != null )
    {
        debugCount.incrementAndGet();
    }

    List<CuratorOp> operations = new ArrayList<>();
    String metaDataBasePath = ZKPaths.makePath(thisMetaDataPath, META_DATA_NODE_NAME);
    toBeApplied.forEach(migration -> {
        List<CuratorOp> thisMigrationOperations = migration.operations();
        operations.addAll(thisMigrationOperations);
        operations.add(client.transactionOp().create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(metaDataBasePath, hash(thisMigrationOperations)));
    });
    return client.transaction().forOperations(operations).thenApply(__ -> null);
}
 
Example #8
Source File: TestMigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testChecksumDataError()
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test");
    CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
    Migration migration = () -> Arrays.asList(op1, op2);
    MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    complete(manager.migrate(migrationSet));

    CuratorOp op2Changed = client.transactionOp().create().forPath("/test/bar", "second".getBytes());
    migration = () -> Arrays.asList(op1, op2Changed);
    migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    try
    {
        complete(manager.migrate(migrationSet));
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof MigrationException);
    }
}
 
Example #9
Source File: TestMigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testChecksumPathError()
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test2");
    CuratorOp op2 = client.transactionOp().create().forPath("/test2/bar");
    Migration migration = () -> Arrays.asList(op1, op2);
    MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    complete(manager.migrate(migrationSet));

    CuratorOp op2Changed = client.transactionOp().create().forPath("/test/bar");
    migration = () -> Arrays.asList(op1, op2Changed);
    migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    try
    {
        complete(manager.migrate(migrationSet));
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof MigrationException);
    }
}
 
Example #10
Source File: TestMigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testPartialApplyForBadOps() throws Exception
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test", "something".getBytes());
    CuratorOp op2 = client.transactionOp().create().forPath("/a/b/c");
    Migration m1 = () -> Collections.singletonList(op1);
    Migration m2 = () -> Collections.singletonList(op2);
    MigrationSet migrationSet = MigrationSet.build("1", Arrays.asList(m1, m2));
    try
    {
        complete(manager.migrate(migrationSet));
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof KeeperException.NoNodeException);
    }

    Assert.assertNull(client.unwrap().checkExists().forPath("/test"));  // should be all or nothing
}
 
Example #11
Source File: TestMigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionForBadOps() throws Exception
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test2", "something".getBytes());
    CuratorOp op2 = client.transactionOp().create().forPath("/a/b/c/d");
    Migration migration = () -> Arrays.asList(op1, op2);
    MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    try
    {
        complete(manager.migrate(migrationSet));
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof KeeperException.NoNodeException);
    }

    Assert.assertNull(client.unwrap().checkExists().forPath("/test"));
}
 
Example #12
Source File: CuratorPersister.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Updates and returns a transaction which can be used to create missing parents of the provided
 * path, if any.
 */
private static List<CuratorOp> createParentsOf(
    CuratorFramework client,
    String path,
    Set<String> existingAndPendingCreatePaths) throws Exception
{
  List<CuratorOp> operations = new ArrayList<>();
  for (String parentPath : PersisterUtils.getParentPaths(path)) {
    if (!existingAndPendingCreatePaths.contains(parentPath)
        && client.checkExists().forPath(parentPath) == null)
    {
      operations.add(client.transactionOp().create().forPath(parentPath));
    }
    existingAndPendingCreatePaths.add(parentPath);
  }
  return operations;
}
 
Example #13
Source File: TestMigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocExample() throws Exception
{
    CuratorOp op1 = client.transactionOp().create().forPath("/parent");
    CuratorOp op2 = client.transactionOp().create().forPath("/parent/one");
    CuratorOp op3 = client.transactionOp().create().forPath("/parent/two");
    CuratorOp op4 = client.transactionOp().create().forPath("/parent/three");
    CuratorOp op5 = client.transactionOp().create().forPath("/main", "hey".getBytes());

    Migration initialMigration = () -> Arrays.asList(op1, op2, op3, op4, op5);
    MigrationSet migrationSet = MigrationSet.build("main", Collections.singletonList(initialMigration));
    complete(manager.migrate(migrationSet));

    Assert.assertNotNull(client.unwrap().checkExists().forPath("/parent/three"));
    Assert.assertEquals(client.unwrap().getData().forPath("/main"), "hey".getBytes());

    CuratorOp newOp1 = client.transactionOp().create().forPath("/new");
    CuratorOp newOp2 = client.transactionOp().delete().forPath("/main");    // maybe this is no longer needed

    Migration newMigration = () -> Arrays.asList(newOp1, newOp2);
    migrationSet = MigrationSet.build("main", Arrays.asList(initialMigration, newMigration));
    complete(manager.migrate(migrationSet));

    Assert.assertNull(client.unwrap().checkExists().forPath("/main"));
}
 
Example #14
Source File: TestBasicOperations.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTransactionWithMode() throws Exception
{
    complete(AsyncWrappers.asyncEnsureContainers(client, "/test"));

    CuratorOp op1 = client.transactionOp().create().withMode(PERSISTENT_SEQUENTIAL).forPath("/test/node-");
    CuratorOp op2 = client.transactionOp().create().withMode(PERSISTENT_SEQUENTIAL).forPath("/test/node-");
    complete(client.transaction().forOperations(Arrays.asList(op1, op2)));

    Assert.assertEquals(client.unwrap().getChildren().forPath("/test").size(), 2);
}
 
Example #15
Source File: TestCompressionInTransactionNew.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple() throws Exception
{
    final String path1 = "/a";
    final String path2 = "/a/b";
    
    final byte[]            data1 = "here's a string".getBytes();
    final byte[]            data2 = "here's another string".getBytes();

    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();

        CuratorOp op1 = client.transactionOp().create().compressed().forPath(path1, data1);
        CuratorOp op2 = client.transactionOp().create().compressed().forPath(path2, data2);

        client.transaction().forOperations(op1, op2);

        Assert.assertNotEquals(data1, client.getData().forPath(path1));
        Assert.assertEquals(data1, client.getData().decompressed().forPath(path1));
        
        Assert.assertNotEquals(data2, client.getData().forPath(path2));
        Assert.assertEquals(data2, client.getData().decompressed().forPath(path2));            
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #16
Source File: Publisher.java    From curator with Apache License 2.0 5 votes vote down vote up
private <T extends Message> void publishMessages(TypedModeledFramework2<T, Group, Priority> typedClient, Group group, List<T> messages)
{
    List<CuratorOp> operations = messages.stream()
        .map(message -> typedClient
                .resolved(client, group, message.getPriority())
                .createOp(message)
            )
        .collect(Collectors.toList());
    client.transaction().forOperations(operations).exceptionally(e -> {
        log.error("Could not publish messages: " + messages, e);
        return null;
    });
}
 
Example #17
Source File: TestCompressionInTransactionNew.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetCompressedAndUncompressed() throws Exception
{
    final String path1 = "/a";
    final String path2 = "/b";
    
    final byte[]            data1 = "here's a string".getBytes();
    final byte[]            data2 = "here's another string".getBytes();

    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();

        //Create the nodes
        CuratorOp op1 = client.transactionOp().create().compressed().forPath(path1);
        CuratorOp op2 = client.transactionOp().create().forPath(path2);
        client.transaction().forOperations(op1, op2);

        //Check they exist
        Assert.assertNotNull(client.checkExists().forPath(path1));
        Assert.assertNotNull(client.checkExists().forPath(path2));
        
        //Set the nodes, path1 compressed, path2 uncompressed.
        op1 = client.transactionOp().setData().compressed().forPath(path1, data1);
        op2 = client.transactionOp().setData().forPath(path2, data2);
        client.transaction().forOperations(op1, op2);
        
        Assert.assertNotEquals(data1, client.getData().forPath(path1));
        Assert.assertEquals(data1, client.getData().decompressed().forPath(path1));
  
        Assert.assertEquals(data2, client.getData().forPath(path2));            
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #18
Source File: TestTransactionsNew.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        CuratorOp createOp1 = client.transactionOp().create().forPath("/foo");
        CuratorOp createOp2 = client.transactionOp().create().forPath("/foo/bar", "snafu".getBytes());

        Collection<CuratorTransactionResult> results = client.transaction().forOperations(createOp1, createOp2);

        Assert.assertTrue(client.checkExists().forPath("/foo/bar") != null);
        Assert.assertEquals(client.getData().forPath("/foo/bar"), "snafu".getBytes());

        CuratorTransactionResult fooResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo"));
        CuratorTransactionResult fooBarResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar"));
        Assert.assertNotNull(fooResult);
        Assert.assertNotNull(fooBarResult);
        Assert.assertNotSame(fooResult, fooBarResult);
        Assert.assertEquals(fooResult.getResultPath(), "/foo");
        Assert.assertEquals(fooBarResult.getResultPath(), "/foo/bar");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #19
Source File: TestTransactionsNew.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithNamespace() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build();
    try
    {
        client.start();
        CuratorOp createOp1 = client.transactionOp().create().forPath("/foo", "one".getBytes());
        CuratorOp createOp2 = client.transactionOp().create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "one".getBytes());
        CuratorOp setDataOp = client.transactionOp().setData().forPath("/foo", "two".getBytes());
        CuratorOp createOp3 = client.transactionOp().create().forPath("/foo/bar");
        CuratorOp deleteOp = client.transactionOp().delete().forPath("/foo/bar");

        Collection<CuratorTransactionResult> results = client.transaction().forOperations(createOp1, createOp2, setDataOp, createOp3, deleteOp);

        Assert.assertTrue(client.checkExists().forPath("/foo") != null);
        Assert.assertTrue(client.usingNamespace(null).checkExists().forPath("/galt/foo") != null);
        Assert.assertEquals(client.getData().forPath("/foo"), "two".getBytes());
        Assert.assertTrue(client.checkExists().forPath("/foo/bar") == null);

        CuratorTransactionResult ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-"));
        Assert.assertNotNull(ephemeralResult);
        Assert.assertNotEquals(ephemeralResult.getResultPath(), "/test-");
        Assert.assertTrue(ephemeralResult.getResultPath().startsWith("/test-"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #20
Source File: Publisher.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * Publish the given instances using the Instance client template in a transaction
 *
 * @param instances instances to publish
 */
public void publishInstances(List<Instance> instances)
{
    List<CuratorOp> operations = instances.stream()
        .map(instance -> Clients.instanceClient
            .resolved(client, instance.getType())
            .createOp(instance)
        )
        .collect(Collectors.toList());
    client.transaction().forOperations(operations).exceptionally(e -> {
        log.error("Could not publish instances: " + instances, e);
        return null;
    });
}
 
Example #21
Source File: TestTransactionsNew.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckVersion() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        client.create().forPath("/foo");
        Stat stat = client.setData().forPath("/foo", "new".getBytes());  // up the version

        CuratorOp statOp = client.transactionOp().check().withVersion(stat.getVersion() + 1).forPath("/foo");
        CuratorOp createOp = client.transactionOp().create().forPath("/bar");
        try
        {
            client.transaction().forOperations(statOp, createOp);
            Assert.fail();
        }
        catch ( KeeperException.BadVersionException correct )
        {
            // correct
        }

        Assert.assertNull(client.checkExists().forPath("/bar"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #22
Source File: TestCompressionInTransactionNew.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * Test the case where both uncompressed and compressed data is generated in
 * the same transaction
 * @throws Exception
 */
@Test
public void testCreateCompressedAndUncompressed() throws Exception
{
    final String path1 = "/a";
    final String path2 = "/b";
    
    final byte[]            data1 = "here's a string".getBytes();
    final byte[]            data2 = "here's another string".getBytes();

    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();

        CuratorOp op1 = client.transactionOp().create().compressed().forPath(path1, data1);
        CuratorOp op2 = client.transactionOp().create().forPath(path2, data2);
        client.transaction().forOperations(op1, op2);

        Assert.assertNotEquals(data1, client.getData().forPath(path1));
        Assert.assertEquals(data1, client.getData().decompressed().forPath(path1));
  
        Assert.assertEquals(data2, client.getData().forPath(path2));            
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #23
Source File: CuratorMultiTransactionImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public List<CuratorTransactionResult> forOperations(List<CuratorOp> operations) throws Exception
{
    operations = Preconditions.checkNotNull(operations, "operations cannot be null");
    Preconditions.checkArgument(!operations.isEmpty(), "operations list cannot be empty");

    CuratorMultiTransactionRecord record = new CuratorMultiTransactionRecord();
    for ( CuratorOp curatorOp : operations )
    {
        Schema schema = client.getSchemaSet().getSchema(curatorOp.getTypeAndPath().getForPath());
        record.add(curatorOp.get(), curatorOp.getTypeAndPath().getType(), curatorOp.getTypeAndPath().getForPath());
        if ( (curatorOp.get().getType() == ZooDefs.OpCode.create) || (curatorOp.get().getType() == ZooDefs.OpCode.createContainer) )
        {
            CreateRequest createRequest = (CreateRequest)curatorOp.get().toRequestRecord();
            CreateMode createMode = CreateMode.fromFlag(createRequest.getFlags(), CreateMode.PERSISTENT);
            schema.validateCreate(createMode, createRequest.getPath(), createRequest.getData(), createRequest.getAcl());
        }
        else if ( (curatorOp.get().getType() == ZooDefs.OpCode.delete) || (curatorOp.get().getType() == ZooDefs.OpCode.deleteContainer) )
        {
            DeleteRequest deleteRequest = (DeleteRequest)curatorOp.get().toRequestRecord();
            schema.validateDelete(deleteRequest.getPath());
        }
        else if ( curatorOp.get().getType() == ZooDefs.OpCode.setData )
        {
            SetDataRequest setDataRequest = (SetDataRequest)curatorOp.get().toRequestRecord();
            schema.validateGeneral(setDataRequest.getPath(), setDataRequest.getData(), null);
        }
    }

    if ( backgrounding.inBackground() )
    {
        client.processBackgroundOperation(new OperationAndData<>(this, record, backgrounding.getCallback(), null, backgrounding.getContext(), null), null);
        return null;
    }
    else
    {
        return forOperationsInForeground(record);
    }
}
 
Example #24
Source File: TestMigrationManager.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrency2() throws Exception
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test");
    CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
    Migration migration = () -> Arrays.asList(op1, op2);
    MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    CountDownLatch latch = new CountDownLatch(1);
    filterLatch.set(latch);
    CompletionStage<Void> first = manager.migrate(migrationSet);
    Assert.assertTrue(timing.awaitLatch(filterIsSetLatch));

    CompletionStage<Void> second = manager.migrate(migrationSet);
    try
    {
        second.toCompletableFuture().get(timing.forSleepingABit().milliseconds(), TimeUnit.MILLISECONDS);
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof TimeoutException, "Should throw TimeoutException, was: " + Throwables.getStackTraceAsString(Throwables.getRootCause(e)));
    }

    latch.countDown();
    complete(first);
    Assert.assertEquals(client.unwrap().getData().forPath("/test/bar"), "first".getBytes());
    complete(second);
    Assert.assertEquals(manager.debugCount.get(), 1);
}
 
Example #25
Source File: TestMigrationManager.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrency1() throws Exception
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test");
    CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
    Migration migration = () -> Arrays.asList(op1, op2);
    MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    CountDownLatch latch = new CountDownLatch(1);
    filterLatch.set(latch);
    CompletionStage<Void> first = manager.migrate(migrationSet);
    Assert.assertTrue(timing.awaitLatch(filterIsSetLatch));

    MigrationManager manager2 = new MigrationManager(client, LOCK_PATH, META_DATA_PATH, executor, Duration.ofMillis(timing.forSleepingABit().milliseconds()));
    try
    {
        complete(manager2.migrate(migrationSet));
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof AsyncWrappers.TimeoutException, "Should throw AsyncWrappers.TimeoutException, was: " + Throwables.getStackTraceAsString(Throwables.getRootCause(e)));
    }

    latch.countDown();
    complete(first);
    Assert.assertEquals(client.unwrap().getData().forPath("/test/bar"), "first".getBytes());
}
 
Example #26
Source File: ModeledFrameworkImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public CuratorOp updateOp(T model, int version)
{
    AsyncTransactionSetDataBuilder builder = client.transactionOp().setData();
    if ( isCompressed() )
    {
        return builder.withVersionCompressed(version).forPath(resolveForSet(model), modelSpec.serializer().serialize(model));
    }
    return builder.withVersion(version).forPath(resolveForSet(model), modelSpec.serializer().serialize(model));
}
 
Example #27
Source File: ModeledFrameworkImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public CuratorOp createOp(T model)
{
    return client.transactionOp()
        .create()
        .withOptions(modelSpec.createMode(), fixAclList(modelSpec.aclList()), modelSpec.createOptions().contains(CreateOption.compress), modelSpec.ttl())
        .forPath(resolveForSet(model), modelSpec.serializer().serialize(model));
}
 
Example #28
Source File: ZooKeeperCommandExecutor.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private void deleteLog(CuratorOp curatorOp, List<String> deleted, String childName) {
    try {
        curator.transaction().forOperations(curatorOp);
        deleted.add(childName);
    } catch (Throwable t) {
        logger.warn("Failed to delete ZooKeeper log: {}", childName, t);
    }
}
 
Example #29
Source File: ModeledFrameworkImpl.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorOp checkExistsOp(int version)
{
    return client.transactionOp().check().withVersion(version).forPath(modelSpec.path().fullPath());
}
 
Example #30
Source File: ModeledFrameworkImpl.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorOp checkExistsOp()
{
    return checkExistsOp(-1);
}