Search in sources :

Example 1 with EventHubException

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

the class Channel method startEventQue.

// ////////  Transaction monitoring  /////////////////////////////
private void startEventQue() {
    if (eventQueueThread != null) {
        return;
    }
    client.getExecutorService().execute(() -> {
        eventQueueThread = Thread.currentThread();
        while (!shutdown) {
            if (!initialized) {
                try {
                    logger.debug("not intialized:" + initialized);
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    logger.warn(e);
                }
                // wait on sending events till the channel is initialized.
                continue;
            }
            final BlockEvent blockEvent;
            try {
                blockEvent = channelEventQue.getNextEvent();
            } catch (EventHubException e) {
                if (!shutdown) {
                    logger.error(e);
                }
                continue;
            }
            if (blockEvent == null) {
                logger.warn("GOT null block event.");
                continue;
            }
            try {
                final String blockchainID = blockEvent.getChannelId();
                final String from = format("Channel %s eventqueue got block event with block number: %d for channel: %s, from %s", name, blockEvent.getBlockNumber(), blockchainID, blockEvent.getPeer() != null ? ("Peer: " + blockEvent.getPeer().getName()) : ("Eventhub: " + blockEvent.getEventHub().getName()));
                logger.trace(from);
                if (!Objects.equals(name, blockchainID)) {
                    logger.warn(format("Channel %s eventqueue got block event NOT FOR ME  channelId %s  from %s", name, blockchainID, from));
                    // not targeted for this channel
                    continue;
                }
                final ArrayList<BL> blcopy = new ArrayList<>(blockListeners.size() + 3);
                synchronized (blockListeners) {
                    blcopy.addAll(blockListeners.values());
                }
                for (BL l : blcopy) {
                    try {
                        logger.trace(format("Sending block event '%s' to block listener %s", from, l.handle));
                        client.getExecutorService().execute(() -> l.listener.received(blockEvent));
                    } catch (Throwable e) {
                        // Don't let one register stop rest.
                        logger.error(format("Error calling block listener %s on channel: %s event: %s ", l.handle, name, from), e);
                    }
                }
            } catch (Exception e) {
                logger.error("Unable to parse event", e);
                logger.debug("event:\n)");
                logger.debug(blockEvent.toString());
            }
        }
    });
}
Also used : ArrayList(java.util.ArrayList) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) ProtoUtils.getSignatureHeaderAsByteString(org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString) ByteString(com.google.protobuf.ByteString) 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 2 with EventHubException

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

the class EventHub method connect.

synchronized boolean connect(final TransactionContext transactionContext, final boolean reconnection) throws EventHubException {
    if (connected) {
        logger.warn(format("%s already connected.", toString()));
        return true;
    }
    eventStream = null;
    final CountDownLatch finishLatch = new CountDownLatch(1);
    logger.debug(format("EventHub %s is connecting.", name));
    lastConnectedAttempt = System.currentTimeMillis();
    Endpoint endpoint = new Endpoint(url, properties);
    managedChannel = endpoint.getChannelBuilder().build();
    clientTLSCertificateDigest = endpoint.getClientTLSCertificateDigest();
    events = EventsGrpc.newStub(managedChannel);
    final ArrayList<Throwable> threw = new ArrayList<>();
    final StreamObserver<PeerEvents.Event> eventStreamLocal = new StreamObserver<PeerEvents.Event>() {

        @Override
        public void onNext(PeerEvents.Event event) {
            logger.debug(format("EventHub %s got  event type: %s", EventHub.this.name, event.getEventCase().name()));
            if (event.getEventCase() == PeerEvents.Event.EventCase.BLOCK) {
                try {
                    BlockEvent blockEvent = new BlockEvent(EventHub.this, event);
                    setLastBlockSeen(blockEvent);
                    // add to channel queue
                    eventQue.addBEvent(blockEvent);
                } catch (InvalidProtocolBufferException e) {
                    EventHubException eventHubException = new EventHubException(format("%s onNext error %s", this, e.getMessage()), e);
                    logger.error(eventHubException.getMessage());
                    threw.add(eventHubException);
                }
            } else if (event.getEventCase() == PeerEvents.Event.EventCase.REGISTER) {
                if (reconnectCount > 1) {
                    logger.info(format("Eventhub %s has reconnecting after %d attempts", name, reconnectCount));
                }
                connected = true;
                connectedTime = System.currentTimeMillis();
                reconnectCount = 0L;
                finishLatch.countDown();
            }
        }

        @Override
        public void onError(Throwable t) {
            connected = false;
            eventStream = null;
            disconnectedTime = System.currentTimeMillis();
            if (shutdown) {
                // IF we're shutdown don't try anything more.
                logger.trace(format("%s was shutdown.", EventHub.this.toString()));
                finishLatch.countDown();
                return;
            }
            final ManagedChannel lmanagedChannel = managedChannel;
            final boolean isTerminated = lmanagedChannel == null ? true : lmanagedChannel.isTerminated();
            final boolean isChannelShutdown = lmanagedChannel == null ? true : lmanagedChannel.isShutdown();
            if (EVENTHUB_RECONNECTION_WARNING_RATE > 1 && reconnectCount % EVENTHUB_RECONNECTION_WARNING_RATE == 1) {
                logger.warn(format("%s terminated is %b shutdown is %b, retry count %d  has error %s.", EventHub.this.toString(), isTerminated, isChannelShutdown, reconnectCount, t.getMessage()));
            } else {
                logger.trace(format("%s terminated is %b shutdown is %b, retry count %d  has error %s.", EventHub.this.toString(), isTerminated, isChannelShutdown, reconnectCount, t.getMessage()));
            }
            finishLatch.countDown();
            // logger.error("Error in stream: " + t.getMessage(), new EventHubException(t));
            if (t instanceof StatusRuntimeException) {
                StatusRuntimeException sre = (StatusRuntimeException) t;
                Status sreStatus = sre.getStatus();
                if (EVENTHUB_RECONNECTION_WARNING_RATE > 1 && reconnectCount % EVENTHUB_RECONNECTION_WARNING_RATE == 1) {
                    logger.warn(format("%s :StatusRuntimeException Status %s.  Description %s ", EventHub.this, sreStatus + "", sreStatus.getDescription()));
                } else {
                    logger.trace(format("%s :StatusRuntimeException Status %s.  Description %s ", EventHub.this, sreStatus + "", sreStatus.getDescription()));
                }
                try {
                    reconnect();
                } catch (Exception e) {
                    logger.warn(format("Eventhub %s Failed shutdown msg:  %s", EventHub.this.name, e.getMessage()));
                }
            }
        }

        @Override
        public void onCompleted() {
            logger.debug(format("Stream completed %s", EventHub.this.toString()));
            finishLatch.countDown();
        }
    };
    sender = events.chat(eventStreamLocal);
    try {
        blockListen(transactionContext);
    } catch (CryptoException e) {
        throw new EventHubException(e);
    }
    try {
        if (!reconnection && !finishLatch.await(EVENTHUB_CONNECTION_WAIT_TIME, TimeUnit.MILLISECONDS)) {
            logger.warn(format("EventHub %s failed to connect in %s ms.", name, EVENTHUB_CONNECTION_WAIT_TIME));
        } else {
            logger.trace(format("Eventhub %s Done waiting for reply!", name));
        }
    } catch (InterruptedException e) {
        logger.error(e);
    }
    logger.debug(format("Eventhub %s connect is done with connect status: %b ", name, connected));
    if (connected) {
        eventStream = eventStreamLocal;
    }
    return connected;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) Status(io.grpc.Status) PeerEvents(org.hyperledger.fabric.protos.peer.PeerEvents) ArrayList(java.util.ArrayList) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) CountDownLatch(java.util.concurrent.CountDownLatch) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) StatusRuntimeException(io.grpc.StatusRuntimeException) ManagedChannel(io.grpc.ManagedChannel) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException)

Aggregations

InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 StatusRuntimeException (io.grpc.StatusRuntimeException)2 ArrayList (java.util.ArrayList)2 CryptoException (org.hyperledger.fabric.sdk.exception.CryptoException)2 EventHubException (org.hyperledger.fabric.sdk.exception.EventHubException)2 InvalidArgumentException (org.hyperledger.fabric.sdk.exception.InvalidArgumentException)2 ByteString (com.google.protobuf.ByteString)1 ManagedChannel (io.grpc.ManagedChannel)1 Status (io.grpc.Status)1 StreamObserver (io.grpc.stub.StreamObserver)1 IOException (java.io.IOException)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 PeerEvents (org.hyperledger.fabric.protos.peer.PeerEvents)1 ProposalException (org.hyperledger.fabric.sdk.exception.ProposalException)1 TransactionEventException (org.hyperledger.fabric.sdk.exception.TransactionEventException)1 TransactionException (org.hyperledger.fabric.sdk.exception.TransactionException)1 ProtoUtils.getSignatureHeaderAsByteString (org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString)1