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

The following examples show how to use org.apache.curator.framework.api.transaction.CuratorTransaction. 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: BaragonStateDatastore.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private void deleteMatchingUpstreams(String serviceId,
                                     Collection<UpstreamInfo> currentUpstreams,
                                     CuratorTransaction transaction,
                                     Set<String> pathsToDelete,
                                     UpstreamInfo upstreamInfo) throws Exception {
  List<String> matchingUpstreamPaths = matchingUpstreamHostPorts(currentUpstreams, upstreamInfo);
  if (matchingUpstreamPaths.isEmpty()) {
    LOG.warn("No upstream node found to delete for {}, current upstream nodes are {}", upstreamInfo, currentUpstreams);
  } else {
    for (String matchingPath : matchingUpstreamPaths) {
      String fullPath = String.format(UPSTREAM_FORMAT, serviceId, matchingPath);
      if (nodeExists(fullPath) && !pathsToDelete.contains(fullPath)) {
        LOG.info("Deleting {}", fullPath);
        pathsToDelete.add(fullPath);
        transaction.delete().forPath(fullPath).and();
      }
    }
  }
}
 
Example #2
Source File: ZkLeaderSelector.java    From binlake with Apache License 2.0 6 votes vote down vote up
/**
 * only startSelector and over can update the counter
 *
 * @param metaInfo
 * @throws Exception
 */
public void updateCounter(MetaInfo metaInfo) throws Exception {
    LogUtils.debug.debug("updateCounter");
    metaInfo.refreshCounter();
    CuratorFramework client = this.client;

    if (client != null) {
        CuratorTransaction trx = client.inTransaction();
        CuratorTransactionFinal trf = trx.setData().forPath(counterPath, Meta.Counter.marshalJson(metaInfo.getCounter())).and();

        Meta.Error err = null;
        if ((err = metaInfo.getError()) != null) {
            trf = trf.setData().forPath(errorPath, Meta.Error.marshalJson(err)).and();
        }
        trf.commit();
    }
}
 
Example #3
Source File: JobNodeStorageTest.java    From shardingsphere-elasticjob-lite with Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void assertExecuteInTransactionFailure() throws Exception {
    CuratorFramework client = mock(CuratorFramework.class);
    CuratorTransaction curatorTransaction = mock(CuratorTransaction.class);
    TransactionCheckBuilder transactionCheckBuilder = mock(TransactionCheckBuilder.class);
    CuratorTransactionBridge curatorTransactionBridge = mock(CuratorTransactionBridge.class);
    CuratorTransactionFinal curatorTransactionFinal = mock(CuratorTransactionFinal.class);
    when(regCenter.getRawClient()).thenReturn(client);
    when(client.inTransaction()).thenReturn(curatorTransaction);
    when(curatorTransaction.check()).thenReturn(transactionCheckBuilder);
    when(transactionCheckBuilder.forPath("/")).thenReturn(curatorTransactionBridge);
    when(curatorTransactionBridge.and()).thenReturn(curatorTransactionFinal);
    when(curatorTransactionBridge.and()).thenThrow(new RuntimeException());
    jobNodeStorage.executeInTransaction(curatorTransactionFinalForCallback -> curatorTransactionFinalForCallback.create().forPath("/test_transaction").and());
    verify(regCenter).getRawClient();
    verify(client).inTransaction();
    verify(curatorTransaction).check();
    verify(transactionCheckBuilder).forPath("/");
    verify(curatorTransactionBridge, times(2)).and();
    verify(curatorTransactionFinal).create();
    verify(curatorTransactionFinal, times(0)).commit();
}
 
Example #4
Source File: JobNodeStorageTest.java    From shardingsphere-elasticjob-lite with Apache License 2.0 6 votes vote down vote up
@Test
public void assertExecuteInTransactionSuccess() throws Exception {
    CuratorFramework client = mock(CuratorFramework.class);
    CuratorTransaction curatorTransaction = mock(CuratorTransaction.class);
    TransactionCheckBuilder transactionCheckBuilder = mock(TransactionCheckBuilder.class);
    CuratorTransactionBridge curatorTransactionBridge = mock(CuratorTransactionBridge.class);
    CuratorTransactionFinal curatorTransactionFinal = mock(CuratorTransactionFinal.class);
    when(regCenter.getRawClient()).thenReturn(client);
    when(client.inTransaction()).thenReturn(curatorTransaction);
    when(curatorTransaction.check()).thenReturn(transactionCheckBuilder);
    when(transactionCheckBuilder.forPath("/")).thenReturn(curatorTransactionBridge);
    when(curatorTransactionBridge.and()).thenReturn(curatorTransactionFinal);
    TransactionCreateBuilder transactionCreateBuilder = mock(TransactionCreateBuilder.class);
    when(curatorTransactionFinal.create()).thenReturn(transactionCreateBuilder);
    when(transactionCreateBuilder.forPath("/test_transaction")).thenReturn(curatorTransactionBridge);
    when(curatorTransactionBridge.and()).thenReturn(curatorTransactionFinal);
    jobNodeStorage.executeInTransaction(curatorTransactionFinalForCallback -> curatorTransactionFinalForCallback.create().forPath("/test_transaction").and());
    verify(regCenter).getRawClient();
    verify(client).inTransaction();
    verify(curatorTransaction).check();
    verify(transactionCheckBuilder).forPath("/");
    verify(curatorTransactionBridge, times(2)).and();
    verify(curatorTransactionFinal).create();
    verify(transactionCreateBuilder).forPath("/test_transaction");
    verify(curatorTransactionFinal).commit();
}
 
Example #5
Source File: CrudDemo.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * Curator支持事务,一组crud操作同生同灭
 * @param client
 */
private static void transation(CuratorFramework client) {
    try {
        // 开启事务
        CuratorTransaction transaction = client.inTransaction();
        Collection<CuratorTransactionResult> results = transaction.create()
                .forPath("/root/transation", "transation".getBytes()).and().create()
                .forPath("/root/transation2", "transation2".getBytes()).and()
                .delete().forPath("/root/transation").and()
                .delete().forPath("/root/transation2").and().commit();
        for (CuratorTransactionResult result : results) {
            System.out.println(result.getForPath() + " - " + result.getType());
        }
    }catch (Exception e){
        log.error("transation exception ", e);
    }
}
 
Example #6
Source File: Curator.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Creates all the given paths in a single transaction. Any paths which already exists are ignored.
 */
public void createAtomically(Path... paths) {
    try {
        CuratorTransaction transaction = framework().inTransaction();
        for (Path path : paths) {
            if ( ! exists(path)) {
                transaction = transaction.create().forPath(path.getAbsolute(), new byte[0]).and();
            }
        }
        ((CuratorTransactionFinal)transaction).commit();
    } catch (Exception e) {
        throw new RuntimeException("Could not create " + Arrays.toString(paths), e);
    }
}
 
Example #7
Source File: DruidPartitionStatus.java    From storm-example with Apache License 2.0 5 votes vote down vote up
public void complete(List<String> partitionIds) throws Exception {
    Iterator<String> iterator = partitionIds.iterator();
    CuratorTransaction transaction = curatorFramework.inTransaction();
    while (iterator.hasNext()) {
        String partitionId = iterator.next();
        transaction = transaction.delete().forPath(LIMBO_PATH + "/" + partitionId)
                .and().create().forPath(COMPLETED_PATH + "/" + partitionId).and();
    }
    CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
    tx.commit();
}
 
Example #8
Source File: DruidBatchStatus.java    From storm-example with Apache License 2.0 5 votes vote down vote up
public void complete(List<Long> txIds) throws Exception {
    Iterator<Long> iterator = txIds.iterator();
    CuratorTransaction transaction = curatorFramework.inTransaction();
    while (iterator.hasNext()) {
        Long txId = iterator.next();
        transaction = transaction.delete().forPath(LIMBO_PATH + "/" + txId)
                .and().create().forPath(COMPLETED_PATH + "/" + txId).and();
    }
    CuratorTransactionFinal tx = (CuratorTransactionFinal) transaction;
    tx.commit();
}
 
Example #9
Source File: ZkService.java    From binlake with Apache License 2.0 5 votes vote down vote up
/**
 * @param c:        curator client
 * @param delPaths: path to delete
 * @param newDbKVs: new db key values
 * @throws Exception
 */
private void refreshDbInfo(CuratorFramework c, List<String> delPaths, Map<String, byte[]> newDbKVs) throws Exception {
    if (delPaths.size() == 0 && newDbKVs.size() == 0) {
        return;
    }

    // transaction
    CuratorTransaction trx = c.inTransaction();
    CuratorTransactionFinal trxf = null;

    for (String p : delPaths) {
        trxf = trx.delete().forPath(p).and();
    }

    for (Map.Entry<String, byte[]> entry : newDbKVs.entrySet()) {
        if (c.checkExists().forPath(entry.getKey()) == null) {
            // node not exist then create
            if (logger.isDebugEnabled()) {
                logger.warn("path " + entry.getKey() + " not exit under zookeeper node " + zkPath);
            }
            trxf = trx.create().forPath(entry.getKey(), entry.getValue()).and();
            continue;
        }
        trxf = trx.setData().forPath(entry.getKey(), entry.getValue()).and();
    }

    trxf.commit();
}
 
Example #10
Source File: CuratorCreateOperation.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public CuratorTransaction and(CuratorTransaction transaction) throws Exception {
    if (data.isPresent()) {
        return transaction.create().forPath(path, data.get()).and();
    } else {
        return transaction.create().forPath(path).and();
    }
}
 
Example #11
Source File: ZkService.java    From binlake with Apache License 2.0 5 votes vote down vote up
/**
 * 批量创建MySQL dump实例
 *
 * @param ms : meta data list
 * @throws Exception
 */
public void batchCreate(List<Meta.MetaData> ms) throws Exception {
    if (ms.size() == 0) {
        logger.warn("no meta info exist on creating znode ");
        return;
    }

    // each time we push one into transaction for share
    Meta.Counter counter = new Meta.Counter().setKillTimes(0).setRetryTimes(0);
    byte[] cbts = Meta.Counter.marshalJson(counter);

    // transaction
    CuratorTransaction trx = client.inTransaction();
    CuratorTransactionFinal trxf = null;

    for (Meta.MetaData metaInfo : ms) {
        // parent path
        String path = zkPath + ApiCenter.makeZNodePath(metaInfo.getDbInfo().getHost(),
                metaInfo.getDbInfo().getPort() + "");

        // create db info node
        Meta.DbInfo dbInfo = metaInfo.getDbInfo();
        for (Map.Entry<String, byte[]> entry : MetaUtils.dbBytesMap(zkPath, dbInfo).entrySet()) {
            logger.debug("create path for " + entry.getKey());
            trxf = trx.create().forPath(entry.getKey(), entry.getValue()).and();
        }

        // other nodes
        Meta.Candidate candidate = new Meta.Candidate().setHost(metaInfo.getCandidate());
        trxf = trx.create().forPath(path + ConstUtils.ZK_DYNAMIC_PATH, Meta.BinlogInfo.marshalJson(metaInfo.getSlave()))
                .and().create().forPath(path + ConstUtils.ZK_COUNTER_PATH, cbts)
                .and().create().forPath(path + ConstUtils.ZK_ERROR_PATH, Meta.Error.marshalJson(Meta.Error.defalut()))
                .and().create().forPath(path + ConstUtils.ZK_ALARM_PATH, Meta.Alarm.marshalJson(metaInfo.getAlarm()))
                .and().create().forPath(path + ConstUtils.ZK_CANDIDATE_PATH, Meta.Candidate.marshalJson(candidate)).and();
    }

    // commit transaction final
    trxf.commit();
}
 
Example #12
Source File: CuratorFrameworkImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public CuratorTransaction inTransaction()
{
    Preconditions.checkState(getState() == CuratorFrameworkState.STARTED, "instance must be started before calling this method");

    return new CuratorTransactionImpl(this);
}
 
Example #13
Source File: ZkService.java    From binlake with Apache License 2.0 5 votes vote down vote up
/**
 * resetCounter 重置计数器 直接进行leader 选举
 *
 * @param host
 * @param port
 * @throws Exception
 */
public void resetCounter(String host, int port) throws Exception {
    logger.debug("resetCounter host : " + host + ", port: " + port);
    String key = ApiCenter.makeZNodePath(host, port + "");
    byte[] dbData = client.getData().forPath(zkPath + key);
    CuratorTransaction tx = client.inTransaction();

    tx.setData().forPath(zkPath + key, dbData).and()
            .setData().forPath(zkPath + key + ConstUtils.ZK_COUNTER_PATH,
            Meta.Counter.marshalJson(new Meta.Counter())).and()
            .commit();
}
 
Example #14
Source File: ZkLeaderSelector.java    From binlake with Apache License 2.0 5 votes vote down vote up
/**
 * update candidates
 *
 * @param cans
 */
private void updateCandidate(byte[] cans, String leader) throws Exception {
    LogUtils.debug.debug("updateCandidate");
    CuratorFramework client = this.client;

    if (client != null) {
        CuratorTransaction trx = client.inTransaction();
        CuratorTransactionFinal ctf = trx.setData().forPath(candidatePath, cans).and();
        if (!StringUtils.equals("", leader)) {
            ctf = ctf.setData().forPath(leaderPath, leader.getBytes()).and();
        }
        // commit
        ctf.commit();
    }
}
 
Example #15
Source File: CuratorTempFrameworkImpl.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorTransaction inTransaction() throws Exception
{
    openConnectionIfNeeded();
    return new CuratorTransactionImpl(client);
}
 
Example #16
Source File: CreateMany.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  for (final Map.Entry<String, byte[]> entry : nodes.entrySet()) {
    transaction.create().forPath(entry.getKey(), entry.getValue());
  }
}
 
Example #17
Source File: CreateEmpty.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  transaction.create().forPath(path, new byte[0]);
}
 
Example #18
Source File: Check.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  transaction.check().forPath(path);
}
 
Example #19
Source File: CreateWithData.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  transaction.create().forPath(path, data);
}
 
Example #20
Source File: SetData.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(CuratorTransaction transaction) throws Exception {
  transaction.setData().forPath(path, bytes);
}
 
Example #21
Source File: CreateWithDataAndVersion.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  transaction
      .create().forPath(path).and()
      .setData().withVersion(version).forPath(path, data);
}
 
Example #22
Source File: DeleteMany.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  for (final String path : paths) {
    transaction.delete().forPath(path);
  }
}
 
Example #23
Source File: CheckWithVersion.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  transaction.check().withVersion(version).forPath(path);
}
 
Example #24
Source File: Delete.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public void register(final CuratorTransaction transaction) throws Exception {
  transaction.delete().forPath(path);
}
 
Example #25
Source File: TransactionExamples.java    From xian with Apache License 2.0 4 votes vote down vote up
public static CuratorTransactionFinal   addCreateToTransaction(CuratorTransaction transaction) throws Exception
{
    // add a create operation
    return transaction.create().forPath("/a/path", "some data".getBytes()).and();
}
 
Example #26
Source File: CuratorFrameworkImpl.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorTransaction inTransaction()
{
    checkState();
    return new CuratorTransactionImpl(this);
}
 
Example #27
Source File: CuratorTempFrameworkImpl.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorTransaction inTransaction() throws Exception
{
    openConnectionIfNeeded();
    return new CuratorTransactionImpl(client);
}
 
Example #28
Source File: MockCurator.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorTransaction inTransaction() {
    return new MockCuratorTransactionFinal();
}
 
Example #29
Source File: CuratorDeleteOperation.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorTransaction and(CuratorTransaction transaction) throws Exception {
    return transaction.delete().forPath(path).and();
}
 
Example #30
Source File: CuratorSetDataOperation.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorTransaction and(CuratorTransaction transaction) throws Exception {
    return transaction.setData().forPath(path, data).and();
}