use of org.hyperledger.fabric.sdk.Channel.PeerOptions in project fabric-sdk-java by hyperledger.
the class Peer method reconnectPeerEventServiceClient.
void reconnectPeerEventServiceClient(final PeerEventServiceClient failedPeerEventServiceClient, final Throwable throwable) {
if (shutdown) {
logger.debug("Not reconnecting PeerEventServiceClient shutdown ");
return;
}
PeerEventingServiceDisconnected ldisconnectedHandler = disconnectedHandler;
if (null == ldisconnectedHandler) {
// just wont reconnect.
return;
}
TransactionContext ltransactionContext = transactionContext;
if (ltransactionContext == null) {
logger.warn("Not reconnecting PeerEventServiceClient no transaction available ");
return;
}
final TransactionContext fltransactionContext = ltransactionContext.retryTransactionSameContext();
final ExecutorService executorService = getExecutorService();
final PeerOptions peerOptions = null != failedPeerEventServiceClient.getPeerOptions() ? failedPeerEventServiceClient.getPeerOptions() : PeerOptions.createPeerOptions();
if (executorService != null && !executorService.isShutdown() && !executorService.isTerminated()) {
executorService.execute(() -> ldisconnectedHandler.disconnected(new PeerEventingServiceDisconnectEvent() {
@Override
public BlockEvent getLatestBLockReceived() {
return lastBlockEvent;
}
@Override
public long getLastConnectTime() {
return lastConnectTime;
}
@Override
public long getReconnectCount() {
return reconnectCount;
}
@Override
public Throwable getExceptionThrown() {
return throwable;
}
@Override
public void reconnect(Long startBLockNumber) throws TransactionException {
logger.trace("reconnecting startBLockNumber" + startBLockNumber);
++reconnectCount;
if (startBLockNumber == null) {
peerOptions.startEventsNewest();
} else {
peerOptions.startEvents(startBLockNumber);
}
PeerEventServiceClient lpeerEventingClient = new PeerEventServiceClient(Peer.this, new Endpoint(url, properties), properties, peerOptions);
lpeerEventingClient.connect(fltransactionContext);
peerEventingClient = lpeerEventingClient;
}
}));
}
}
use of org.hyperledger.fabric.sdk.Channel.PeerOptions in project fabric-sdk-java by hyperledger.
the class NetworkConfig method reconstructChannel.
// Reconstructs an existing channel
private Channel reconstructChannel(HFClient client, String channelName, JsonObject jsonChannel) throws NetworkConfigurationException {
Channel channel = null;
try {
channel = client.newChannel(channelName);
// orderers is an array of orderer name strings
JsonArray ordererNames = getJsonValueAsArray(jsonChannel.get("orderers"));
boolean foundOrderer = false;
// out("Orderer names: " + (ordererNames == null ? "null" : ordererNames.toString()));
if (ordererNames != null) {
for (JsonValue jsonVal : ordererNames) {
String ordererName = getJsonValueAsString(jsonVal);
Orderer orderer = getOrderer(client, ordererName);
if (orderer == null) {
throw new NetworkConfigurationException(format("Error constructing channel %s. Orderer %s not defined in configuration", channelName, ordererName));
}
channel.addOrderer(orderer);
foundOrderer = true;
}
}
if (!foundOrderer) {
// orderers is a required field
throw new NetworkConfigurationException(format("Error constructing channel %s. At least one orderer must be specified", channelName));
}
// peers is an object containing a nested object for each peer
JsonObject jsonPeers = getJsonObject(jsonChannel, "peers");
boolean foundPeer = false;
// out("Peers: " + (peers == null ? "null" : peers.toString()));
if (jsonPeers != null) {
for (Entry<String, JsonValue> entry : jsonPeers.entrySet()) {
String peerName = entry.getKey();
if (logger.isTraceEnabled()) {
logger.trace(format("NetworkConfig.reconstructChannel: Processing peer %s", peerName));
}
JsonObject jsonPeer = getJsonValueAsObject(entry.getValue());
if (jsonPeer == null) {
throw new NetworkConfigurationException(format("Error constructing channel %s. Invalid peer entry: %s", channelName, peerName));
}
Peer peer = getPeer(client, peerName);
if (peer == null) {
throw new NetworkConfigurationException(format("Error constructing channel %s. Peer %s not defined in configuration", channelName, peerName));
}
// Set the various roles
PeerOptions peerOptions = PeerOptions.createPeerOptions();
setPeerRole(channelName, peerOptions, jsonPeer, PeerRole.ENDORSING_PEER);
setPeerRole(channelName, peerOptions, jsonPeer, PeerRole.CHAINCODE_QUERY);
setPeerRole(channelName, peerOptions, jsonPeer, PeerRole.LEDGER_QUERY);
setPeerRole(channelName, peerOptions, jsonPeer, PeerRole.EVENT_SOURCE);
channel.addPeer(peer, peerOptions);
foundPeer = true;
// Add the event hub associated with this peer
EventHub eventHub = getEventHub(client, peerName);
if (eventHub == null) {
// By rights this should never happen!
throw new NetworkConfigurationException(format("Error constructing channel %s. EventHub for %s not defined in configuration", channelName, peerName));
}
channel.addEventHub(eventHub);
}
}
if (!foundPeer) {
// peers is a required field
throw new NetworkConfigurationException(format("Error constructing channel %s. At least one peer must be specified", channelName));
}
} catch (InvalidArgumentException e) {
throw new IllegalArgumentException(e);
}
return channel;
}
use of org.hyperledger.fabric.sdk.Channel.PeerOptions in project fabric-sdk-java by hyperledger.
the class End2endAndBackAgainIT method testPeerServiceEventingReplay.
/**
* This code test the replay feature of the new peer event services.
* Instead of the default of starting the eventing peer to retrieve the newest block it sets it
* retrieve starting from the start parameter. Also checks with block and filterblock replays.
* Depends on end2end and end2endAndBackagain of have fully run to have the blocks need to work with.
*
* @param client
* @param replayTestChannel
* @param start
* @param stop
* @param useFilteredBlocks
* @throws InvalidArgumentException
*/
private void testPeerServiceEventingReplay(HFClient client, Channel replayTestChannel, final long start, final long stop, final boolean useFilteredBlocks) throws InvalidArgumentException {
if (testConfig.isRunningAgainstFabric10()) {
// not supported for v1.0
return;
}
// not yet initialized
assertFalse(replayTestChannel.isInitialized());
// not yet shutdown.
assertFalse(replayTestChannel.isShutdown());
// Remove all peers just have one ledger peer and one eventing peer.
List<Peer> savedPeers = new ArrayList<>(replayTestChannel.getPeers());
for (Peer peer : savedPeers) {
replayTestChannel.removePeer(peer);
}
// need at least two
assertTrue(savedPeers.size() > 1);
final Peer eventingPeer = savedPeers.remove(0);
Peer ledgerPeer = savedPeers.remove(0);
// no more peers.
assertTrue(replayTestChannel.getPeers().isEmpty());
// just checking :)
assertTrue(replayTestChannel.getPeers(EnumSet.of(PeerRole.CHAINCODE_QUERY, PeerRole.ENDORSING_PEER)).isEmpty());
// just checking
assertTrue(replayTestChannel.getPeers(EnumSet.of(PeerRole.LEDGER_QUERY)).isEmpty());
// should be known by client.
assertNotNull(client.getChannel(replayTestChannel.getName()));
final PeerOptions eventingPeerOptions = createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.EVENT_SOURCE));
if (useFilteredBlocks) {
eventingPeerOptions.registerEventsForFilteredBlocks();
}
if (-1L == stop) {
// the height of the blockchain
// Eventing peer start getting blocks from block 0
replayTestChannel.addPeer(eventingPeer, eventingPeerOptions.startEvents(start));
} else {
replayTestChannel.addPeer(eventingPeer, eventingPeerOptions.startEvents(start).stopEvents(// Eventing peer start getting blocks from block 0
stop));
}
// add a ledger peer
replayTestChannel.addPeer(ledgerPeer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.LEDGER_QUERY)));
// future to set when done.
CompletableFuture<Long> done = new CompletableFuture<>();
// some variable used by the block listener being set up.
final AtomicLong bcount = new AtomicLong(0);
final AtomicLong stopValue = new AtomicLong(stop == -1L ? Long.MAX_VALUE : stop);
final Channel finalChannel = replayTestChannel;
final Map<Long, BlockEvent> blockEvents = Collections.synchronizedMap(new HashMap<>(100));
final String blockListenerHandle = replayTestChannel.registerBlockListener(blockEvent -> {
try {
final long blockNumber = blockEvent.getBlockNumber();
BlockEvent seen = blockEvents.put(blockNumber, blockEvent);
assertNull(format("Block number %d seen twice", blockNumber), seen);
assertTrue(format("Wrong type of block seen block number %d. expected filtered block %b but got %b", blockNumber, useFilteredBlocks, blockEvent.isFiltered()), useFilteredBlocks ? blockEvent.isFiltered() : !blockEvent.isFiltered());
// count starts with 0 not 1 !
final long count = bcount.getAndIncrement();
if (count == 0 && stop == -1L) {
final BlockchainInfo blockchainInfo = finalChannel.queryBlockchainInfo();
long lh = blockchainInfo.getHeight();
// blocks 0L 9L are on chain height 10 .. stop on 9
stopValue.set(lh - 1L);
// out("height: %d", lh);
if (bcount.get() + start > stopValue.longValue()) {
// test with latest count.
// report back latest count.
done.complete(bcount.get());
}
} else {
if (bcount.longValue() + start > stopValue.longValue()) {
done.complete(count);
}
}
} catch (AssertionError | Exception e) {
e.printStackTrace();
done.completeExceptionally(e);
}
});
try {
// start it all up.
replayTestChannel.initialize();
// give a timeout here.
done.get(30, TimeUnit.SECONDS);
// sleep a little to see if more blocks trickle in .. they should not
Thread.sleep(1000);
replayTestChannel.unregisterBlockListener(blockListenerHandle);
// Start 2 and stop is 3 expect 2
final long expectNumber = stopValue.longValue() - start + 1L;
assertEquals(format("Didn't get number we expected %d but got %d block events. Start: %d, end: %d, height: %d", expectNumber, blockEvents.size(), start, stop, stopValue.longValue()), expectNumber, blockEvents.size());
for (long i = stopValue.longValue(); i >= start; i--) {
// make sure all are there.
final BlockEvent blockEvent = blockEvents.get(i);
assertNotNull(format("Missing block event for block number %d. Start= %d", i, start), blockEvent);
}
// light weight test just see if we get reasonable values for traversing the block. Test just whats common between
// Block and FilteredBlock.
int transactionEventCounts = 0;
int chaincodeEventsCounts = 0;
for (long i = stopValue.longValue(); i >= start; i--) {
final BlockEvent blockEvent = blockEvents.get(i);
// out("blockwalker %b, start: %d, stop: %d, i: %d, block %d", useFilteredBlocks, start, stopValue.longValue(), i, blockEvent.getBlockNumber());
// check again
assertEquals(useFilteredBlocks, blockEvent.isFiltered());
if (useFilteredBlocks) {
// should not have raw block event.
assertNull(blockEvent.getBlock());
// should have raw filtered block.
assertNotNull(blockEvent.getFilteredBlock());
} else {
// should not have raw block event.
assertNotNull(blockEvent.getBlock());
// should have raw filtered block.
assertNull(blockEvent.getFilteredBlock());
}
assertEquals(replayTestChannel.getName(), blockEvent.getChannelId());
for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {
if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) {
BlockInfo.TransactionEnvelopeInfo transactionEnvelopeInfo = (BlockInfo.TransactionEnvelopeInfo) envelopeInfo;
// only have valid blocks.
assertTrue(envelopeInfo.isValid());
assertEquals(envelopeInfo.getValidationCode(), 0);
++transactionEventCounts;
for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo ta : transactionEnvelopeInfo.getTransactionActionInfos()) {
// out("\nTA:", ta + "\n\n");
ChaincodeEvent event = ta.getEvent();
if (event != null) {
assertNotNull(event.getChaincodeId());
assertNotNull(event.getEventName());
chaincodeEventsCounts++;
}
}
} else {
assertEquals("Only non transaction block should be block 0.", blockEvent.getBlockNumber(), 0);
}
}
}
assertTrue(transactionEventCounts > 0);
if (expectNumber > 4) {
// this should be enough blocks with CC events.
assertTrue(chaincodeEventsCounts > 0);
}
// all done.
replayTestChannel.shutdown(true);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
Aggregations