Example usage for com.google.common.util.concurrent CheckedFuture checkedGet

List of usage examples for com.google.common.util.concurrent CheckedFuture checkedGet

Introduction

In this page you can find the example usage for com.google.common.util.concurrent CheckedFuture checkedGet.

Prototype

V checkedGet() throws X;

Source Link

Document

Exception checking version of Future#get() that will translate InterruptedException , CancellationException and ExecutionException into application-specific exceptions.

Usage

From source file:org.opendaylight.unimgr.utils.OvsdbUtils.java

/**
 * Deletes a generic node.//from   w  w  w  . j  av  a2s  . co m
 * @param dataBroker The instance of the data broker to create transactions
 * @param store The DataStore where the delete
 * @param path The path to delete
 * @return An instance of a generic Data Object
 */
public <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean delete(DataBroker dataBroker,
        final LogicalDatastoreType store, final InstanceIdentifier<D> path) {
    boolean result = false;
    final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
    transaction.delete(store, path);
    final CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    try {
        future.checkedGet();
        result = true;
    } catch (final TransactionCommitFailedException e) {
        LOG.warn("Failed to delete {} ", path, e);
    }
    return result;
}

From source file:org.opendaylight.distributed.tx.it.provider.datawriter.DtxDataStoreSyncWriter.java

/**
 * Synchronously write to datastore with distributed-tx API
 *//*  w  w w.ja v a 2 s.  co m*/
@Override
public void writeData() {
    int putsPerTx = input.getPutsPerTx();
    int counter = 0;
    List<OuterList> outerLists = dataStoreListBuilder.buildOuterList();

    if (input.getOperation() == OperationType.DELETE) {
        dataStoreListBuilder.buildTestInnerList();
    }

    InstanceIdentifier<DatastoreTestData> nodeId = InstanceIdentifier.create(DatastoreTestData.class);

    dtx = dTxProvider.newTx(nodesMap);
    startTime = System.nanoTime();
    for (OuterList outerList : outerLists) {
        for (InnerList innerList : outerList.getInnerList()) {
            InstanceIdentifier<InnerList> innerIid = InstanceIdentifier.create(DatastoreTestData.class)
                    .child(OuterList.class, outerList.getKey()).child(InnerList.class, innerList.getKey());

            CheckedFuture<Void, DTxException> writeFuture;
            if (input.getOperation() == OperationType.PUT) {
                writeFuture = dtx.putAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, innerList, nodeId);
            } else if (input.getOperation() == OperationType.MERGE) {
                writeFuture = dtx.mergeAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, innerList, nodeId);
            } else {
                writeFuture = dtx.deleteAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, nodeId);
            }
            counter++;

            try {
                writeFuture.checkedGet();
            } catch (Exception e) {
                txError++;
                counter = 0;
                dtx = dTxProvider.newTx(nodesMap);
                continue;
            }

            if (counter == putsPerTx) {
                CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dtx.submit();
                try {
                    submitFuture.checkedGet();
                    txSucceed++;
                } catch (TransactionCommitFailedException e) {
                    txError++;
                }
                counter = 0;
                dtx = dTxProvider.newTx(nodesMap);
            }
        }
    }

    CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit();
    try {
        restSubmitFuture.checkedGet();
        txSucceed++;
    } catch (Exception e) {
        txError++;
    }
    endTime = System.nanoTime();
}

From source file:org.opendaylight.controller.clustering.it.provider.MdsalLowLevelTestProvider.java

@Override
@SuppressWarnings("checkstyle:IllegalCatch")
public Future<RpcResult<UnsubscribeDdtlOutput>> unsubscribeDdtl() {
    LOG.debug("Received unsubscribe-ddtl.");

    if (idIntsDdtl == null || ddtlReg == null) {
        final RpcError error = RpcResultBuilder.newError(ErrorType.RPC, "Ddtl missing.",
                "No DOMDataTreeListener registered.");
        return Futures
                .immediateFuture(RpcResultBuilder.<UnsubscribeDdtlOutput>failed().withRpcError(error).build());
    }//ww w .j  a v  a 2 s . com

    try {
        idIntsDdtl.tryFinishProcessing().get(120, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        final RpcError error = RpcResultBuilder.newError(ErrorType.RPC, "resource-denied-transport",
                "Unable to finish notification processing in 120 seconds.", "clustering-it", "clustering-it",
                e);
        return Futures
                .immediateFuture(RpcResultBuilder.<UnsubscribeDdtlOutput>failed().withRpcError(error).build());
    }

    ddtlReg.close();
    ddtlReg = null;

    if (!idIntsDdtl.hasTriggered()) {
        final RpcError error = RpcResultBuilder.newError(ErrorType.APPLICATION, "No notification received.",
                "id-ints listener has not received" + "any notifications.");
        return Futures
                .immediateFuture(RpcResultBuilder.<UnsubscribeDdtlOutput>failed().withRpcError(error).build());
    }

    final String shardName = ClusterUtils.getCleanShardName(ProduceTransactionsHandler.ID_INTS_YID);
    LOG.debug("Creating distributed datastore client for shard {}", shardName);

    final ActorContext actorContext = configDataStore.getActorContext();
    final Props distributedDataStoreClientProps = SimpleDataStoreClientActor
            .props(actorContext.getCurrentMemberName(), "Shard-" + shardName, actorContext, shardName);

    final ActorRef clientActor = actorSystem.actorOf(distributedDataStoreClientProps);
    final DataStoreClient distributedDataStoreClient;
    try {
        distributedDataStoreClient = SimpleDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30,
                TimeUnit.SECONDS);
    } catch (RuntimeException e) {
        LOG.error("Failed to get actor for {}", distributedDataStoreClientProps, e);
        clientActor.tell(PoisonPill.getInstance(), noSender());
        final RpcError error = RpcResultBuilder.newError(ErrorType.APPLICATION,
                "Unable to create ds client for read.", "Unable to create ds client for read.");
        return Futures
                .immediateFuture(RpcResultBuilder.<UnsubscribeDdtlOutput>failed().withRpcError(error).build());
    }

    final ClientLocalHistory localHistory = distributedDataStoreClient.createLocalHistory();
    final ClientTransaction tx = localHistory.createTransaction();
    final CheckedFuture<Optional<NormalizedNode<?, ?>>, org.opendaylight.mdsal.common.api.ReadFailedException> read = tx
            .read(YangInstanceIdentifier.of(ProduceTransactionsHandler.ID_INT));

    tx.abort();
    localHistory.close();
    try {
        final Optional<NormalizedNode<?, ?>> optional = read.checkedGet();
        if (!optional.isPresent()) {
            LOG.warn("Final read from client is empty.");
            final RpcError error = RpcResultBuilder.newError(ErrorType.APPLICATION, "Read failed.",
                    "Final read from id-ints is empty.");
            return Futures.immediateFuture(
                    RpcResultBuilder.<UnsubscribeDdtlOutput>failed().withRpcError(error).build());
        }

        return Futures.immediateFuture(RpcResultBuilder.success(
                new UnsubscribeDdtlOutputBuilder().setCopyMatches(idIntsDdtl.checkEqual(optional.get())))
                .build());

    } catch (org.opendaylight.mdsal.common.api.ReadFailedException e) {
        LOG.error("Unable to read data to verify ddtl data.", e);
        final RpcError error = RpcResultBuilder.newError(ErrorType.APPLICATION, "Read failed.",
                "Final read from id-ints failed.");
        return Futures
                .immediateFuture(RpcResultBuilder.<UnsubscribeDdtlOutput>failed().withRpcError(error).build());
    } finally {
        distributedDataStoreClient.close();
        clientActor.tell(PoisonPill.getInstance(), noSender());
    }
}

From source file:org.opendaylight.vtn.manager.it.ofmock.impl.OfMockProvider.java

/**
 * Return the global configuration for VTN Manager.
 *
 * @return  A {@link VtnConfig} instance.
 * @throws Exception  An error occurred.
 *//*from w ww. j a  v a  2  s . c  o  m*/
private VtnConfig getVtnConfig() throws Exception {
    VtnConfig vcfg = vtnConfig;
    if (vcfg == null) {
        // Load configuration from MD-SAL datastore.
        InstanceIdentifier<VtnConfig> path = InstanceIdentifier.create(VtnConfig.class);
        ReadOnlyTransaction rtx = dataBroker.newReadOnlyTransaction();
        CheckedFuture<Optional<VtnConfig>, ReadFailedException> f = rtx.read(LogicalDatastoreType.OPERATIONAL,
                path);
        Optional<VtnConfig> opt = f.checkedGet();
        vcfg = opt.get();
        vtnConfig = vcfg;
    }

    return vcfg;
}

From source file:org.opendaylight.distributed.tx.it.provider.datawriter.DtxNetConfSyncWriter.java

/**
 * Synchronously write to NetConf device with distributed-tx API
 *///from w  w w . j a  va  2s . c  o m
@Override
public void writeData() {
    long putsPerTx = input.getPutsPerTx();
    List<NodeId> nodeIdList = new ArrayList(nodeIdSet);
    Set<InstanceIdentifier<?>> txIidSet = new HashSet<>();
    NodeId n = nodeIdList.get(0);
    InstanceIdentifier msNodeId = NETCONF_TOPO_IID.child(Node.class, new NodeKey(n));
    int counter = 0;
    InterfaceName ifName = nodeIfList.get(n).get(0);

    if (input.getOperation() == OperationType.DELETE) {
        //Build subInterfaces for delete operation
        configInterface();
    }

    txIidSet.add(msNodeId);
    dtx = dTxProvider.newTx(txIidSet);
    startTime = System.nanoTime();

    for (int i = 1; i <= input.getLoop(); i++) {
        KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                        new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), ifName));
        InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder();
        interfaceConfigurationBuilder.setInterfaceName(ifName);

        interfaceConfigurationBuilder
                .setDescription(DTXITConstants.TEST_DESCRIPTION + input.getOperation() + i);
        interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
        InterfaceConfiguration config = interfaceConfigurationBuilder.build();

        CheckedFuture<Void, DTxException> writeFuture = null;
        if (input.getOperation() == OperationType.PUT) {
            writeFuture = dtx.putAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER,
                    LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config, msNodeId);
        } else if (input.getOperation() == OperationType.MERGE) {
            writeFuture = dtx.mergeAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER,
                    LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config, msNodeId);
        } else {
            InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
            KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> subSpecificInterfaceCfgIid = netconfIid
                    .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                            new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
            writeFuture = dtx.deleteAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER,
                    LogicalDatastoreType.CONFIGURATION, subSpecificInterfaceCfgIid, msNodeId);
        }
        counter++;

        try {
            writeFuture.checkedGet();
        } catch (Exception e) {
            txError++;
            counter = 0;
            dtx = dTxProvider.newTx(txIidSet);
            continue;
        }

        if (counter == putsPerTx) {
            CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dtx.submit();
            try {
                submitFuture.checkedGet();
                txSucceed++;
            } catch (TransactionCommitFailedException e) {
                txError++;
            }
            counter = 0;
            dtx = this.dTxProvider.newTx(txIidSet);
        }
    }

    CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit();
    try {
        restSubmitFuture.checkedGet();
        txSucceed++;
    } catch (Exception e) {
        txError++;
    }
    endTime = System.nanoTime();
}

From source file:org.opendaylight.distributed.tx.it.provider.DistributedTxProviderImpl.java

/**
 * Initialize datastore for performance test and integrated test
 *//*  w w  w  .j a  v a 2  s .  c om*/
public boolean initializeDataStoreTestData(int outerElements) {
    LOG.info("Initialize datastore data tree");
    InstanceIdentifier<DatastoreTestData> iid = InstanceIdentifier.create(DatastoreTestData.class);

    WriteTransaction transaction = this.dataBroker.newWriteOnlyTransaction();
    DatastoreTestData datastoreTestData = new DatastoreTestDataBuilder().build();
    transaction.put(LogicalDatastoreType.CONFIGURATION, iid, datastoreTestData);
    CheckedFuture<Void, TransactionCommitFailedException> cf = transaction.submit();

    try {
        cf.checkedGet();
    } catch (Exception e) {
        LOG.trace("Can't put datastoreTestData to datastore for {}", e);
        return false;
    }

    List<OuterList> outerLists = buildOuterList(outerElements);
    for (OuterList outerList : outerLists) {
        transaction = this.dataBroker.newWriteOnlyTransaction();
        InstanceIdentifier<OuterList> outerIid = InstanceIdentifier.create(DatastoreTestData.class)
                .child(OuterList.class, outerList.getKey());

        transaction.put(LogicalDatastoreType.CONFIGURATION, outerIid, outerList);
        CheckedFuture<Void, TransactionCommitFailedException> submitFut = transaction.submit();
        try {
            submitFut.checkedGet();
        } catch (Exception e) {
            LOG.trace("Can't put outerList to the datastore for {}", e);
            return false;
        }
    }
    return true;
}

From source file:org.opendaylight.distributed.tx.it.provider.DistributedTxProviderImpl.java

/**
 * Build test subInterfaces for delete operation
 *///  w w w  . j  av  a 2 s.  co m
public boolean buildTestInterfaces(DataBroker xrNodeBroker, long numberOfIfs) {
    WriteTransaction xrNodeWriteTx = null;
    InstanceIdentifier<InterfaceConfigurations> netconfIid = InstanceIdentifier
            .create(InterfaceConfigurations.class);
    for (int i = 1; i <= numberOfIfs; i++) {
        xrNodeWriteTx = xrNodeBroker.newWriteOnlyTransaction();
        InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
        final KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                        new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
        final InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder();
        interfaceConfigurationBuilder.setInterfaceName(subIfName);
        interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
        InterfaceConfiguration config = interfaceConfigurationBuilder.build();

        xrNodeWriteTx.put(LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config);
        CheckedFuture<Void, TransactionCommitFailedException> submitFut = xrNodeWriteTx.submit();
        try {
            submitFut.checkedGet();
        } catch (TransactionCommitFailedException e) {
            LOG.trace("Building test configuration fail for {}", e);
            return false;
        }
    }
    return true;
}

From source file:org.opendaylight.distributed.tx.it.provider.DistributedTxProviderImpl.java

/**
 * Initialize netconf configurations// w  w  w.j av  a 2 s  .  co  m
 * delete subInterface if it exists
 */
public void deleteInterfaces(DataBroker xrNodeBroker, int numberOfTxs) {
    InstanceIdentifier<InterfaceConfigurations> netconfIid = InstanceIdentifier
            .create(InterfaceConfigurations.class);

    for (int i = 1; i <= numberOfTxs; i++) {
        ReadWriteTransaction writeTx = xrNodeBroker.newReadWriteTransaction();
        InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
        KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                        new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
        CheckedFuture<Optional<InterfaceConfiguration>, ReadFailedException> readFuture = writeTx
                .read(LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid);
        Optional<InterfaceConfiguration> readResult = Optional.absent();
        try {
            readResult = readFuture.checkedGet();
        } catch (ReadFailedException e) {
            LOG.trace("Can't read the original config of the {} subInterface", subIfName.toString());
        }

        if (readResult.isPresent()) {
            writeTx.delete(LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid);
        }

        CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTx.submit();
        try {
            submitFuture.checkedGet();
        } catch (TransactionCommitFailedException e) {
            LOG.trace("Delete fail");
        }
    }
}

From source file:org.opendaylight.distributed.tx.it.provider.DistributedTxProviderImpl.java

/**
 * DTx datastore integration test// w  w w .j  a  v a  2s  .co  m
 * normal test: DTx can write to the datastore
 * rollback-on-failure test: DTx can rollback when submit fails
 * rollback test: DTx can rollback manually before submit
 */
@Override
public Future<RpcResult<DatastoreTestOutput>> datastoreTest(DatastoreTestInput input) {
    int putsPerTx = input.getPutsPerTx();
    int outerElements = input.getOuterList(), innerElements = input.getInnerList();
    OperationType operation = input.getOperation();
    Map<DTXLogicalTXProviderType, Set<InstanceIdentifier<?>>> nodesMap = new HashMap<>();
    Set<InstanceIdentifier<?>> nodeIdSet = new HashSet<>();
    DataStoreListBuilder dataStoreListBuilder = new DataStoreListBuilder(dataBroker, outerElements,
            innerElements);
    List<OuterList> outerLists = dataStoreListBuilder.buildOuterList();
    InstanceIdentifier<DatastoreTestData> nodeId = InstanceIdentifier.create(DatastoreTestData.class);
    long count = 0;
    //Indicating the result of test
    boolean testSucceed = true;

    LOG.info("Start DTx datastore test");

    if (dsTestStatus.compareAndSet(TestStatus.ExecStatus.Idle, TestStatus.ExecStatus.Executing) == false) {
        return RpcResultBuilder
                .success(new DatastoreTestOutputBuilder().setStatus(StatusType.TESTINPROGRESS).build())
                .buildFuture();
    }

    nodeIdSet.add(InstanceIdentifier.create(DatastoreTestData.class));
    nodesMap.put(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER, nodeIdSet);

    if (!initializeDataStoreTestData(outerElements)) {
        LOG.info("Can't initialize test data for DTx datastore test");
        dsTestStatus.set(TestStatus.ExecStatus.Idle);
        return RpcResultBuilder.success(new DatastoreTestOutputBuilder().setStatus(StatusType.FAILED).build())
                .buildFuture();
    }
    //Build test data first if the oeration is delete
    if (operation == OperationType.DELETE)
        dataStoreListBuilder.buildTestInnerList();

    DTx dTx = dTxProvider.newTx(nodesMap);

    if (input.getType() != TestType.NORMAL) {
        if (input.getType() == TestType.ROLLBACKONFAILURE) {
            /**
             * DTx write innerLists to datastore
             * one of operations failed for nonexistent parent node
             * DTx submit fails and performs rollback
             * ensure data in datastore is correct after rollback
             */
            LOG.info("Start DTx datastore rollback on failure test");
            //Error instance identifier point to a node without parent
            InstanceIdentifier<InnerList> errorInnerIid = InstanceIdentifier.create(DatastoreTestData.class)
                    .child(OuterList.class, new OuterListKey(outerElements))
                    .child(InnerList.class, new InnerListKey(0));

            InnerList errorInnerlist = new InnerListBuilder().setKey(new InnerListKey(0))
                    .setValue("Error InnerList").setName(0).build();
            int errorOccur = (int) (putsPerTx * (Math.random())) + 1;//ensure the errorOccur not be zero

            for (OuterList outerList : outerLists) {
                for (InnerList innerList : outerList.getInnerList()) {
                    InstanceIdentifier<InnerList> InnerIid = getInstanceIdentifier(outerList, innerList);
                    //Write to datastore with normal data iid
                    CheckedFuture<Void, DTxException> writeFuture = writeData(dTx, operation,
                            DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                            InnerIid, nodeId, innerList);

                    try {
                        writeFuture.checkedGet();
                    } catch (DTxException e) {
                        LOG.trace("Write failed for {}", e.toString());
                    }

                    count++;

                    if (count == errorOccur) {
                        //Write to datastore with error iid
                        writeFuture = writeData(dTx, operation, DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                                LogicalDatastoreType.CONFIGURATION, errorInnerIid, nodeId, errorInnerlist);
                    }

                    try {
                        writeFuture.checkedGet();
                    } catch (DTxException e) {
                        // Even write to error iid, writing future still succeed
                        LOG.info("Write failed for {}", e.toString());
                    }

                    if (count == putsPerTx) {
                        CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dTx.submit();
                        try {
                            submitFuture.checkedGet();
                            testSucceed = false;
                        } catch (Exception e) {
                            //Submit fails
                            LOG.info("Get submit exception {}", e.toString());
                        }
                        count = 0;
                        //Get another DTx from provider because DTx will become unavailable after each submit
                        dTx = dTxProvider.newTx(nodesMap);
                    }
                }
            }
        } else {
            LOG.info("Start DTx datastore rollback test");
            /**
             * DTx write innerLists to datastore
             * manually trigger rollback of all operations
             * ensure data in datastore is correct after rollback
             */
            for (OuterList outerList : outerLists) {
                for (InnerList innerList : outerList.getInnerList()) {
                    InstanceIdentifier<InnerList> InnerIid = getInstanceIdentifier(outerList, innerList);
                    CheckedFuture<Void, DTxException> writeFuture = writeData(dTx, operation,
                            DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                            InnerIid, nodeId, innerList);

                    try {
                        writeFuture.checkedGet();
                    } catch (DTxException e) {
                        LOG.info("Write failed for {}", e.toString());
                    }
                    count++;

                    if (count == putsPerTx) {
                        //Trigger rollback
                        CheckedFuture<Void, DTxException.RollbackFailedException> rollbackFuture = dTx
                                .rollback();
                        try {
                            rollbackFuture.checkedGet();
                        } catch (Exception e) {
                            LOG.info("Get rollback exception {}", e.toString());
                            testSucceed = false;
                        }
                        count = 0;
                        dTx = dTxProvider.newTx(nodesMap);
                    }
                }
            }
        }
        //Outstanding submit make sure all DTxs have been finished
        CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dTx.submit();
        try {
            restSubmitFuture.checkedGet();
        } catch (TransactionCommitFailedException e) {
            LOG.info("DTx outstanding submit failed for {}", e.toString());
        }
        //Check out data in datastore to ensure rollback succeed
        for (OuterList outerList : outerLists) {
            for (InnerList innerList : outerList.getInnerList()) {
                InstanceIdentifier<InnerList> innerIid = getInstanceIdentifier(outerList, innerList);
                ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
                //Read data from datastore
                CheckedFuture<Optional<InnerList>, ReadFailedException> readFuture = tx
                        .read(LogicalDatastoreType.CONFIGURATION, innerIid);
                Optional<InnerList> result = Optional.absent();
                try {
                    result = readFuture.checkedGet();
                } catch (ReadFailedException readException) {
                    testSucceed = false;
                }
                if (operation != OperationType.DELETE) {
                    if (result.isPresent()) {
                        testSucceed = false;
                    }
                } else {
                    if (!result.isPresent()) {
                        testSucceed = false;
                    }
                }
            }
        }
    } else {
        LOG.info("Start DTx datastore normal test");
        /**
         * DTx write innerLists to datastore
         * ensure data in datastore is correct
         */
        for (OuterList outerList : outerLists) {
            for (InnerList innerList : outerList.getInnerList()) {
                InstanceIdentifier<InnerList> InnerIid = getInstanceIdentifier(outerList, innerList);
                CheckedFuture<Void, DTxException> writeFuture = writeData(dTx, operation,
                        DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                        InnerIid, nodeId, innerList);
                count++;

                try {
                    writeFuture.checkedGet();
                } catch (DTxException e) {
                    LOG.info("Write failed for {}", e.toString());
                }

                if (count == putsPerTx) {
                    CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dTx.submit();
                    try {
                        submitFuture.checkedGet();
                    } catch (TransactionCommitFailedException e) {
                        LOG.info("DTx transaction submit fail for {}", e.toString());
                    }
                    dTx = dTxProvider.newTx(nodesMap);
                    count = 0;
                }
            }
        }

        CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dTx.submit();
        try {
            restSubmitFuture.checkedGet();
        } catch (TransactionCommitFailedException e) {
            LOG.info("DTx outstanding submit fail for {}", e.toString());
        }
        //Check whether all innerLists have been written to datastore
        for (OuterList outerList : outerLists) {
            for (InnerList innerList : outerList.getInnerList()) {
                InstanceIdentifier<InnerList> innerIid = getInstanceIdentifier(outerList, innerList);
                ReadTransaction transaction = dataBroker.newReadOnlyTransaction();
                //Read data from datastore
                CheckedFuture<Optional<InnerList>, ReadFailedException> readFuture = transaction
                        .read(LogicalDatastoreType.CONFIGURATION, innerIid);
                Optional<InnerList> result = Optional.absent();
                try {
                    result = readFuture.checkedGet();
                } catch (ReadFailedException e) {
                    LOG.info("Can't read the data from the data store");
                    testSucceed = false;
                }
                if (operation != OperationType.DELETE) {
                    if (!result.isPresent()) {
                        testSucceed = false;
                    }
                } else {
                    if (result.isPresent()) {
                        testSucceed = false;
                    }
                }
            }
        }
    }
    LOG.info("DTx datastore test finishs");
    dsTestStatus.set(TestStatus.ExecStatus.Idle);
    if (testSucceed == true) {
        return RpcResultBuilder.success(new DatastoreTestOutputBuilder().setStatus(StatusType.OK).build())
                .buildFuture();
    } else {
        return RpcResultBuilder.success(new DatastoreTestOutputBuilder().setStatus(StatusType.FAILED).build())
                .buildFuture();
    }
}

From source file:org.opendaylight.distributed.tx.it.provider.DistributedTxProviderImpl.java

/**
 * DTx netconf integration test/* w ww.j a  v  a 2 s.  c o m*/
 * normal test: DTx can write to multiple netconf nodes
 * rollback-on-failure test: DTx can rollback upon all netconf nodes when operation fails
 * rollback test: DTx can rollback manually before submit
 */
@Override
public Future<RpcResult<NetconfTestOutput>> netconfTest(NetconfTestInput input) {
    int putsPerTx = input.getPutsPerTx();
    OperationType operation = input.getOperation();
    int counter = 0;
    boolean testSucceed = true;

    List<NodeId> nodeIdList = new ArrayList(nodeIdSet);
    Set<InstanceIdentifier<?>> txIidSet = new HashSet<>();

    NodeId n1 = nodeIdList.get(0);
    InstanceIdentifier nodeId1 = NETCONF_TOPO_IID.child(Node.class, new NodeKey(n1));
    txIidSet.add(nodeId1);

    NodeId n2 = nodeIdList.get(1);
    InstanceIdentifier nodeId2 = NETCONF_TOPO_IID.child(Node.class, new NodeKey(n2));
    txIidSet.add(nodeId2);

    InstanceIdentifier<InterfaceConfigurations> netconfIid = InstanceIdentifier
            .create(InterfaceConfigurations.class);
    //Get xrNodeBroker for corresponding netconf node from the map
    DataBroker xrNodeBroker1 = xrNodeBrokerMap.get(DTXITConstants.XRV_NAME1);
    DataBroker xrNodeBroker2 = xrNodeBrokerMap.get(DTXITConstants.XRV_NAME2);

    LOG.info("Start DTx netconf test");
    if (netConfTestStatus.compareAndSet(TestStatus.ExecStatus.Idle, TestStatus.ExecStatus.Executing) == false) {
        return RpcResultBuilder
                .success(new NetconfTestOutputBuilder().setStatus(StatusType.TESTINPROGRESS).build())
                .buildFuture();
    }
    //Delete existing subInterfaces in netconf node1
    deleteInterfaces(xrNodeBroker1, input.getNumberOfTxs());
    //Delete existing subInterfaces in netconf node2
    deleteInterfaces(xrNodeBroker2, input.getNumberOfTxs());
    if (input.getOperation() == OperationType.DELETE) {
        if (!buildTestInterfaces(xrNodeBroker1, input.getNumberOfTxs())) {
            LOG.info("Can't build test subInterfaces for DTx netconf node1");
            netConfTestStatus.set(TestStatus.ExecStatus.Idle);
            return RpcResultBuilder.success(new NetconfTestOutputBuilder().setStatus(StatusType.FAILED).build())
                    .buildFuture();
        }

        if (!buildTestInterfaces(xrNodeBroker2, input.getNumberOfTxs())) {
            LOG.info("Can't build test subInterfaces for DTx netconf node2");
            netConfTestStatus.set(TestStatus.ExecStatus.Idle);
            return RpcResultBuilder.success(new NetconfTestOutputBuilder().setStatus(StatusType.FAILED).build())
                    .buildFuture();
        }
    }

    if (input.getType() != TestType.NORMAL) {
        if (input.getType() == TestType.ROLLBACKONFAILURE) {
            /**
             * DTx write data to netconf node1 and netconf node2
             * when deleting a nonexistent subInterface, exception occurs and DTx performs rollback
             * check data in netconf devices to ensure rollback succeed
             */
            LOG.info("Start DTx netconf rollback on failure test");
            //Delete subInterface GigabitEthernet0/0/0/1.1 in netconf node2
            deleteInterfaces(xrNodeBroker2, 1);
            DTx dtx = dTxProvider.newTx(txIidSet);
            //This iid is illegal because it points to an nonexistent subInterface
            InterfaceName errorIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + 1);
            KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> errorSpecificInterfaceCfgIid = netconfIid
                    .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                            new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), errorIfName));
            InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder();
            interfaceConfigurationBuilder.setInterfaceName(errorIfName);
            interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
            InterfaceConfiguration errorConfig = interfaceConfigurationBuilder.build();

            for (int i = 1; i <= input.getNumberOfTxs(); i++) {
                InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
                KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                        .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                                new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
                InterfaceConfigurationBuilder interfaceConfigurationBuilder2 = new InterfaceConfigurationBuilder();
                interfaceConfigurationBuilder2.setInterfaceName(subIfName);
                interfaceConfigurationBuilder2.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
                InterfaceConfiguration config = interfaceConfigurationBuilder2.build();

                //Write to netconf node1
                CheckedFuture<Void, DTxException> writeFuture = writeData(dtx, operation,
                        DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                        specificInterfaceCfgIid, nodeId1, config);
                counter++;

                try {
                    writeFuture.checkedGet();
                } catch (Exception e) {
                    LOG.trace("put failed for {}", e.toString());
                }

                if (counter == putsPerTx) {
                    //Delete a nonexistent subInterface to trigger error
                    writeFuture = writeData(dtx, OperationType.DELETE,
                            DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                            errorSpecificInterfaceCfgIid, nodeId2, errorConfig);

                    try {
                        writeFuture.checkedGet();
                        testSucceed = false;
                    } catch (Exception e) {
                        LOG.trace("Write failed for {}", e.toString());
                    }
                    counter = 0;
                    dtx = dTxProvider.newTx(txIidSet);
                }
            }
            CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit();
            try {
                restSubmitFuture.checkedGet();
            } catch (Exception e) {
                LOG.trace("Outstanding submit failed for {}", e.toString());
                testSucceed = false;
            }
        } else {
            LOG.info("Start DTx netconf rollback test");
            /**
             * DTx write to netconf node1
             * manually rollback all the operations on netconf node1
             * check data in netconf node to ensure rollback succeed
             */
            DTx dtx = dTxProvider.newTx(txIidSet);
            for (int i = 1; i <= input.getNumberOfTxs(); i++) {
                InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
                KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                        .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                                new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
                InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder();
                interfaceConfigurationBuilder.setInterfaceName(subIfName);
                interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
                InterfaceConfiguration config = interfaceConfigurationBuilder.build();

                //Write to netconf node1
                CheckedFuture<Void, DTxException> writeFuture = writeData(dtx, operation,
                        DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                        specificInterfaceCfgIid, nodeId1, config);
                counter++;

                try {
                    writeFuture.checkedGet();
                } catch (Exception e) {
                    LOG.trace("Write failed for {}", e.toString());
                }

                if (counter == putsPerTx) {
                    CheckedFuture<Void, DTxException.RollbackFailedException> rollbackFuture = dtx.rollback();
                    try {
                        rollbackFuture.checkedGet();
                    } catch (Exception e) {
                        LOG.trace("DTx netconf rollback failed for {}", e.toString());
                        testSucceed = false;
                    }
                    counter = 0;
                    dtx = dTxProvider.newTx(txIidSet);
                }
            }
            CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit();
            try {
                restSubmitFuture.checkedGet();
            } catch (Exception e) {
                LOG.trace("Outstanding submit failed for {}", e.toString());
            }
        }
        //Ensure data in netconf node is correct after rollback
        for (int i = 1; i <= input.getNumberOfTxs(); i++) {
            InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
            KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                    .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                            new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
            ReadOnlyTransaction netconfTx1 = xrNodeBroker1.newReadOnlyTransaction();

            //Read data from netconf node1
            CheckedFuture<Optional<InterfaceConfiguration>, ReadFailedException> netconfReadFuture1 = netconfTx1
                    .read(LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid);
            Optional<InterfaceConfiguration> netconfResult1 = Optional.absent();

            try {
                netconfResult1 = netconfReadFuture1.checkedGet();
            } catch (ReadFailedException e) {
                testSucceed = false;
                LOG.info("Can't read the data from the device");
            }
            if (operation != OperationType.DELETE) {
                if (netconfResult1.isPresent()) {
                    testSucceed = false;
                }
            } else {
                if (!netconfResult1.isPresent()) {
                    testSucceed = false;
                }
            }
        }
    } else {
        LOG.info("Start DTx Netconf normal test");
        /**
         * DTx write data to both netconf node1 and netconf node2
         * ensure data has been written to netconf nodes
         */
        DTx dtx = dTxProvider.newTx(txIidSet);
        for (int i = 1; i <= input.getNumberOfTxs(); i++) {
            InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
            KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                    .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                            new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
            InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder();
            interfaceConfigurationBuilder.setInterfaceName(subIfName);
            interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
            InterfaceConfiguration config = interfaceConfigurationBuilder.build();

            //Write to netconf node1
            CheckedFuture<Void, DTxException> writeFuture1 = writeData(dtx, operation,
                    DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                    specificInterfaceCfgIid, nodeId1, config);
            //Write to netconf node2
            CheckedFuture<Void, DTxException> writeFuture2 = writeData(dtx, operation,
                    DTXLogicalTXProviderType.NETCONF_TX_PROVIDER, LogicalDatastoreType.CONFIGURATION,
                    specificInterfaceCfgIid, nodeId2, config);
            counter++;

            try {
                writeFuture1.checkedGet();
            } catch (Exception e) {
                LOG.trace("Write to netConf node1 failed for {}", e.toString());
            }

            try {
                writeFuture2.checkedGet();
            } catch (Exception e) {
                LOG.trace("Write to netConf node2 failed for {}", e.toString());
            }

            if (counter == putsPerTx) {
                CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dtx.submit();
                try {
                    submitFuture.checkedGet();
                } catch (Exception e) {
                    LOG.trace("Submit failed for {}", e.toString());
                }
                counter = 0;
                dtx = dTxProvider.newTx(txIidSet);
            }
        }
        CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit();
        try {
            restSubmitFuture.checkedGet();
        } catch (TransactionCommitFailedException e) {
            LOG.trace("Get outstanding submit exception {}", e.toString());
        }
        //Check data in netconf nodes to ensure rollback succeed
        for (int i = 1; i <= input.getNumberOfTxs(); i++) {
            InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
            KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                    .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                            new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
            ReadOnlyTransaction netconfTx1 = xrNodeBroker1.newReadOnlyTransaction();
            ReadOnlyTransaction netconfTx2 = xrNodeBroker2.newReadOnlyTransaction();

            //Read data from netconf node1
            CheckedFuture<Optional<InterfaceConfiguration>, ReadFailedException> netconfReadFuture1 = netconfTx1
                    .read(LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid);
            //Read data from netconf node2
            CheckedFuture<Optional<InterfaceConfiguration>, ReadFailedException> netconfReadFuture2 = netconfTx2
                    .read(LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid);
            Optional<InterfaceConfiguration> netonfResult1 = Optional.absent();
            Optional<InterfaceConfiguration> netconfResult2 = Optional.absent();

            try {
                netonfResult1 = netconfReadFuture1.checkedGet();
            } catch (ReadFailedException e) {
                LOG.trace("Can't read data from netconf node1");
                testSucceed = false;
            }

            try {
                netconfResult2 = netconfReadFuture2.checkedGet();
            } catch (ReadFailedException e) {
                LOG.trace("Can't read data from netconf node2");
                testSucceed = false;
            }
            if (operation != OperationType.DELETE) {
                if (!netonfResult1.isPresent() && !netconfResult2.isPresent()) {
                    testSucceed = false;
                }
            } else {
                if (netonfResult1.isPresent() && netconfResult2.isPresent()) {
                    testSucceed = false;
                }
            }
        }
    }
    LOG.info("DTx netconf test finishs");
    netConfTestStatus.set(TestStatus.ExecStatus.Idle);
    if (testSucceed == true) {
        return RpcResultBuilder.success(new NetconfTestOutputBuilder().setStatus(StatusType.OK).build())
                .buildFuture();
    } else {
        return RpcResultBuilder.success(new NetconfTestOutputBuilder().setStatus(StatusType.FAILED).build())
                .buildFuture();
    }
}