Search in sources :

Example 11 with TransactionException

use of org.hyperledger.fabric.sdk.exception.TransactionException in project fabric-sdk-java by hyperledger.

the class Channel method seekBlock.

private int seekBlock(SeekInfo seekInfo, List<DeliverResponse> deliverResponses, Orderer ordererIn) throws TransactionException {
    logger.trace(format("seekBlock for channel %s", name));
    final long start = System.currentTimeMillis();
    @SuppressWarnings("UnusedAssignment") int statusRC = 404;
    try {
        do {
            statusRC = 404;
            final Orderer orderer = ordererIn != null ? ordererIn : getRandomOrderer();
            TransactionContext txContext = getTransactionContext();
            DeliverResponse[] deliver = orderer.sendDeliver(createSeekInfoEnvelope(txContext, seekInfo, orderer.getClientTLSCertificateDigest()));
            if (deliver.length < 1) {
                logger.warn(format("Genesis block for channel %s fetch bad deliver missing status block only got blocks:%d", name, deliver.length));
                // odd so lets try again....
                statusRC = 404;
            } else {
                DeliverResponse status = deliver[0];
                statusRC = status.getStatusValue();
                if (statusRC == 404 || statusRC == 503) {
                    // 404 - block not found.  503 - service not available usually means kafka is not ready but starting.
                    logger.warn(format("Bad deliver expected status 200  got  %d, Channel %s", status.getStatusValue(), name));
                    // keep trying... else
                    statusRC = 404;
                } else if (statusRC != 200) {
                    // Assume for anything other than 200 we have a non retryable situation
                    throw new TransactionException(format("Bad newest block expected status 200  got  %d, Channel %s", status.getStatusValue(), name));
                } else {
                    if (deliver.length < 2) {
                        throw new TransactionException(format("Newest block for channel %s fetch bad deliver missing genesis block only got %d:", name, deliver.length));
                    } else {
                        deliverResponses.addAll(Arrays.asList(deliver));
                    }
                }
            }
            if (200 != statusRC) {
                long duration = System.currentTimeMillis() - start;
                if (duration > config.getGenesisBlockWaitTime()) {
                    throw new TransactionException(format("Getting block time exceeded %s seconds for channel %s", Long.toString(TimeUnit.MILLISECONDS.toSeconds(duration)), name));
                }
                try {
                    // try again
                    Thread.sleep(ORDERER_RETRY_WAIT_TIME);
                } catch (InterruptedException e) {
                    TransactionException te = new TransactionException("seekBlock thread Sleep", e);
                    logger.warn(te.getMessage(), te);
                }
            }
        } while (statusRC != 200);
    } catch (TransactionException e) {
        logger.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new TransactionException(e);
    }
    return statusRC;
}
Also used : TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionContext(org.hyperledger.fabric.sdk.transaction.TransactionContext) DeliverResponse(org.hyperledger.fabric.protos.orderer.Ab.DeliverResponse) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) TimeoutException(java.util.concurrent.TimeoutException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException)

Example 12 with TransactionException

use of org.hyperledger.fabric.sdk.exception.TransactionException in project fabric-sdk-java by hyperledger.

the class Channel method getGenesisBlock.

private Block getGenesisBlock(Orderer orderer) throws TransactionException {
    try {
        if (genesisBlock != null) {
            logger.debug(format("Channel %s getGenesisBlock already present", name));
        } else {
            final long start = System.currentTimeMillis();
            SeekSpecified seekSpecified = SeekSpecified.newBuilder().setNumber(0).build();
            SeekPosition seekPosition = SeekPosition.newBuilder().setSpecified(seekSpecified).build();
            SeekSpecified seekStopSpecified = SeekSpecified.newBuilder().setNumber(0).build();
            SeekPosition seekStopPosition = SeekPosition.newBuilder().setSpecified(seekStopSpecified).build();
            SeekInfo seekInfo = SeekInfo.newBuilder().setStart(seekPosition).setStop(seekStopPosition).setBehavior(SeekInfo.SeekBehavior.BLOCK_UNTIL_READY).build();
            ArrayList<DeliverResponse> deliverResponses = new ArrayList<>();
            seekBlock(seekInfo, deliverResponses, orderer);
            DeliverResponse blockresp = deliverResponses.get(1);
            Block configBlock = blockresp.getBlock();
            if (configBlock == null) {
                throw new TransactionException(format("In getGenesisBlock newest block for channel %s fetch bad deliver returned null:", name));
            }
            int dataCount = configBlock.getData().getDataCount();
            if (dataCount < 1) {
                throw new TransactionException(format("In getGenesisBlock bad config block data count %d", dataCount));
            }
            genesisBlock = blockresp.getBlock();
        }
    } catch (TransactionException e) {
        logger.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        TransactionException exp = new TransactionException("getGenesisBlock " + e.getMessage(), e);
        logger.error(exp.getMessage(), exp);
        throw exp;
    }
    if (genesisBlock == null) {
        // make sure it was really set.
        TransactionException exp = new TransactionException("getGenesisBlock returned null");
        logger.error(exp.getMessage(), exp);
        throw exp;
    }
    logger.debug(format("Channel %s getGenesisBlock done.", name));
    return genesisBlock;
}
Also used : SeekInfo(org.hyperledger.fabric.protos.orderer.Ab.SeekInfo) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) SeekPosition(org.hyperledger.fabric.protos.orderer.Ab.SeekPosition) SeekSpecified(org.hyperledger.fabric.protos.orderer.Ab.SeekSpecified) ArrayList(java.util.ArrayList) Block(org.hyperledger.fabric.protos.common.Common.Block) DeliverResponse(org.hyperledger.fabric.protos.orderer.Ab.DeliverResponse) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) TimeoutException(java.util.concurrent.TimeoutException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException)

Example 13 with TransactionException

use of org.hyperledger.fabric.sdk.exception.TransactionException in project fabric-sdk-java by hyperledger.

the class Channel method getChannelConfigurationBytes.

/**
 * Channel Configuration bytes. Bytes that can be used with configtxlator tool to upgrade the channel.
 * Convert to Json for editing  with:
 * {@code
 * <p>
 * curl -v   POST --data-binary @fooConfig http://host/protolator/decode/common.Config
 * <p>
 * }
 * See http://hyperledger-fabric.readthedocs.io/en/latest/configtxlator.html
 *
 * @return Channel configuration bytes.
 * @throws TransactionException
 */
public byte[] getChannelConfigurationBytes() throws TransactionException {
    try {
        final Block configBlock = getConfigBlock(getShuffledPeers());
        Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0));
        Payload payload = Payload.parseFrom(envelopeRet.getPayload());
        ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData());
        return configEnvelope.getConfig().toByteArray();
    } catch (Exception e) {
        throw new TransactionException(e);
    }
}
Also used : TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) ConfigEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigEnvelope) Block(org.hyperledger.fabric.protos.common.Common.Block) Payload(org.hyperledger.fabric.protos.common.Common.Payload) ConfigEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigEnvelope) ConfigUpdateEnvelope(org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope) Envelope(org.hyperledger.fabric.protos.common.Common.Envelope) ProtoUtils.createSeekInfoEnvelope(org.hyperledger.fabric.sdk.transaction.ProtoUtils.createSeekInfoEnvelope) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) TimeoutException(java.util.concurrent.TimeoutException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException)

Example 14 with TransactionException

use of org.hyperledger.fabric.sdk.exception.TransactionException in project fabric-sdk-java by hyperledger.

the class Channel method initialize.

/**
 * Initialize the Channel.  Starts the channel. event hubs will connect.
 *
 * @return this channel.
 * @throws InvalidArgumentException
 * @throws TransactionException
 */
public Channel initialize() throws InvalidArgumentException, TransactionException {
    logger.debug(format("Channel %s initialize shutdown %b", name, shutdown));
    if (shutdown) {
        throw new InvalidArgumentException(format("Channel %s has been shutdown.", name));
    }
    if (isNullOrEmpty(name)) {
        throw new InvalidArgumentException("Can not initialize channel without a valid name.");
    }
    if (client == null) {
        throw new InvalidArgumentException("Can not initialize channel without a client object.");
    }
    userContextCheck(client.getUserContext());
    try {
        // put all MSP certs into cryptoSuite if this fails here we'll try again later.
        loadCACertificates();
    } catch (Exception e) {
        logger.warn(format("Channel %s could not load peer CA certificates from any peers.", name));
    }
    try {
        logger.debug(format("Eventque started %s", "" + eventQueueThread));
        for (EventHub eh : eventHubs) {
            // Connect all event hubs
            eh.connect(getTransactionContext());
        }
        for (Peer peer : getEventingPeers()) {
            peer.initiateEventing(getTransactionContext(), getPeersOptions(peer));
        }
        logger.debug(format("%d eventhubs initialized", getEventHubs().size()));
        // Manage transactions.
        registerTransactionListenerProcessor();
        logger.debug(format("Channel %s registerTransactionListenerProcessor completed", name));
        // Run the event for event messages from event hubs.
        startEventQue();
        this.initialized = true;
        logger.debug(format("Channel %s initialized", name));
        return this;
    // } catch (TransactionException e) {
    // logger.error(e.getMessage(), e);
    // throw e;
    } catch (Exception e) {
        TransactionException exp = new TransactionException(e);
        logger.error(exp.getMessage(), exp);
        throw exp;
    }
}
Also used : InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) TimeoutException(java.util.concurrent.TimeoutException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException)

Example 15 with TransactionException

use of org.hyperledger.fabric.sdk.exception.TransactionException in project fabric-sdk-java by hyperledger.

the class OrdererClient method sendTransaction.

Ab.BroadcastResponse sendTransaction(Common.Envelope envelope) throws Exception {
    StreamObserver<Common.Envelope> nso = null;
    if (shutdown) {
        throw new TransactionException("Orderer client is shutdown");
    }
    ManagedChannel lmanagedChannel = managedChannel;
    if (lmanagedChannel == null || lmanagedChannel.isTerminated() || lmanagedChannel.isShutdown()) {
        lmanagedChannel = channelBuilder.build();
        managedChannel = lmanagedChannel;
    }
    try {
        final CountDownLatch finishLatch = new CountDownLatch(1);
        AtomicBroadcastGrpc.AtomicBroadcastStub broadcast = AtomicBroadcastGrpc.newStub(lmanagedChannel);
        final Ab.BroadcastResponse[] ret = new Ab.BroadcastResponse[1];
        final Throwable[] throwable = new Throwable[] { null };
        StreamObserver<Ab.BroadcastResponse> so = new StreamObserver<Ab.BroadcastResponse>() {

            @Override
            public void onNext(Ab.BroadcastResponse resp) {
                // logger.info("Got Broadcast response: " + resp);
                logger.debug("resp status value: " + resp.getStatusValue() + ", resp: " + resp.getStatus());
                if (resp.getStatus() == Common.Status.SUCCESS) {
                    ret[0] = resp;
                } else {
                    throwable[0] = new TransactionException(format("Channel %s orderer %s status returned failure code %d (%s) during order registration", channelName, name, resp.getStatusValue(), resp.getStatus().name()));
                }
                finishLatch.countDown();
            }

            @Override
            public void onError(Throwable t) {
                if (!shutdown) {
                    logger.error(format("Received error on channel %s, orderer %s, url %s, %s", channelName, name, url, t.getMessage()), t);
                }
                throwable[0] = t;
                finishLatch.countDown();
            }

            @Override
            public void onCompleted() {
                finishLatch.countDown();
            }
        };
        nso = broadcast.broadcast(so);
        nso.onNext(envelope);
        try {
            if (!finishLatch.await(ordererWaitTimeMilliSecs, TimeUnit.MILLISECONDS)) {
                TransactionException ste = new TransactionException(format("Channel %s, send transactions failed on orderer %s. Reason:  timeout after %d ms.", channelName, name, ordererWaitTimeMilliSecs));
                logger.error("sendTransaction error " + ste.getMessage(), ste);
                throw ste;
            }
            if (throwable[0] != null) {
                // get full stack trace
                TransactionException ste = new TransactionException(format("Channel %s, send transaction failed on orderer %s. Reason: %s", channelName, name, throwable[0].getMessage()), throwable[0]);
                logger.error("sendTransaction error " + ste.getMessage(), ste);
                throw ste;
            }
            logger.debug("Done waiting for reply! Got:" + ret[0]);
        } catch (InterruptedException e) {
            logger.error(e);
        }
        return ret[0];
    } catch (Throwable t) {
        managedChannel = null;
        throw t;
    } finally {
        if (null != nso) {
            try {
                nso.onCompleted();
            } catch (Exception e) {
                // Best effort only report on debug
                logger.debug(format("Exception completing sendTransaction with channel %s,  name %s, url %s %s", channelName, name, url, e.getMessage()), e);
            }
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) Ab(org.hyperledger.fabric.protos.orderer.Ab) AtomicBroadcastGrpc(org.hyperledger.fabric.protos.orderer.AtomicBroadcastGrpc) CountDownLatch(java.util.concurrent.CountDownLatch) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) ManagedChannel(io.grpc.ManagedChannel)

Aggregations

TransactionException (org.hyperledger.fabric.sdk.exception.TransactionException)15 CryptoException (org.hyperledger.fabric.sdk.exception.CryptoException)11 StatusRuntimeException (io.grpc.StatusRuntimeException)10 InvalidArgumentException (org.hyperledger.fabric.sdk.exception.InvalidArgumentException)10 ProposalException (org.hyperledger.fabric.sdk.exception.ProposalException)10 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)9 IOException (java.io.IOException)9 ExecutionException (java.util.concurrent.ExecutionException)9 TimeoutException (java.util.concurrent.TimeoutException)9 EventHubException (org.hyperledger.fabric.sdk.exception.EventHubException)9 TransactionEventException (org.hyperledger.fabric.sdk.exception.TransactionEventException)9 Block (org.hyperledger.fabric.protos.common.Common.Block)6 ArrayList (java.util.ArrayList)5 Envelope (org.hyperledger.fabric.protos.common.Common.Envelope)5 DeliverResponse (org.hyperledger.fabric.protos.orderer.Ab.DeliverResponse)5 ProtoUtils.createSeekInfoEnvelope (org.hyperledger.fabric.sdk.transaction.ProtoUtils.createSeekInfoEnvelope)5 ConfigEnvelope (org.hyperledger.fabric.protos.common.Configtx.ConfigEnvelope)4 ConfigUpdateEnvelope (org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope)4 ByteString (com.google.protobuf.ByteString)3 ManagedChannel (io.grpc.ManagedChannel)3