Skip to content

Commit

Permalink
FABN-1348 NodeSDK allow targets with discovery
Browse files Browse the repository at this point in the history
Allow the targets parameter to override the discovery plan.

Signed-off-by: Bret Harrison <[email protected]>
Change-Id: Iaba2989a6888cdfe03da436dde4fbe0dbd042f4c
  • Loading branch information
harrisob committed Aug 22, 2019
1 parent 6418070 commit b06fda4
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 17 deletions.
13 changes: 10 additions & 3 deletions fabric-client/lib/Channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -2871,8 +2871,13 @@ const Channel = class {
}

// convert any names into peer objects or if empty find all
// endorsing peers added to this channel
request.targets = this._getTargets(request.targets, Constants.NetworkConfig.ENDORSING_PEER_ROLE);
// endorsing peers added to this channel if discovery is off
if (!this._use_discovery || request.targets) {
logger.debug('%s - checking for targets');
request.targets = this._getTargets(request.targets, Constants.NetworkConfig.ENDORSING_PEER_ROLE);
} else {
logger.debug('%s - discovery is on and no targets');
}

// always use the handler if available (may not be just for discovery)
if (this._endorsement_handler) {
Expand Down Expand Up @@ -4141,7 +4146,9 @@ const Channel = class {
const state = {
name: this._name,
orderers: orderers.length > 0 ? orderers : 'N/A',
peers: peers.length > 0 ? peers : 'N/A'
peers: peers.length > 0 ? peers : 'N/A',
discovery: this._use_discovery,
number: this._number
};

return JSON.stringify(state).toString();
Expand Down
7 changes: 6 additions & 1 deletion fabric-client/lib/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ const Client = class extends BaseClient {
* @returns {Channel} The channel instance
*/
getChannel(name, throwError = true) {
const method = 'getChannel';
let channel;
if (name) {
channel = this._channels.get(name);
Expand All @@ -348,6 +349,7 @@ const Client = class extends BaseClient {
}

if (channel) {
logger.debug('%s - returning existing channel %s', method, name);
return channel;
}

Expand All @@ -358,11 +360,14 @@ const Client = class extends BaseClient {
name = channel_names[0];
}
if (name) {
logger.debug('%s - building new channel from network config %s', method, name);
channel = this._network_config.getChannel(name);
}
}
if (channel) {
this._channels.set(name, channel);
logger.debug('%s - returning new channel %s', method, name);

return channel;
}

Expand Down Expand Up @@ -1963,4 +1968,4 @@ module.exports.Orderer = Orderer;
module.exports.Channel = Channel;
module.exports.User = User;
module.exports.Package = Package;
module.exports.Chaincode = Chaincode;
module.exports.Chaincode = Chaincode;
4 changes: 2 additions & 2 deletions fabric-client/lib/impl/DiscoveryEndorsementHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ class DiscoveryEndorsementHandler extends EndorsementHandler {
timeout = params.timeout;
}

// when not using discovery
if (!params.use_discovery) {
// when targets specified then do not use discovery
if (params.request.targets) {
logger.debug('%s - running without discovery', method);
const responses = await client_utils.sendPeersProposal(params.request.targets, params.signed_proposal, timeout);

Expand Down
25 changes: 20 additions & 5 deletions test/integration/discovery.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,11 +282,20 @@ test('\n\n***** D I S C O V E R Y *****\n\n', async (t) => {

const force_target_request = {
chaincodeId: first_chaincode_name,
target: 'peer0.org1.example.com'
targets: ['peer0.org1.example.com:7051']
};
await testUtil.invokeAsAdmin(t, client_org1, channel_org1, force_target_request);

t.pass('***** Invokes and Queries complete *****');
const bad_target_request = {
chaincodeId: first_chaincode_name,
targets: [peer_bad]
};
try {
await testUtil.invokeAsAdmin(t, client_org1, channel_org1, bad_target_request, true);
t.fail('Failed to get the error with a bad target');
} catch (error) {
t.pass('Successfully got the error with a bad target' + error);
}

const tx_id = client_org1.newTransactionID(true);
tx_id_string = tx_id.getTransactionID();
Expand All @@ -308,6 +317,7 @@ test('\n\n***** D I S C O V E R Y *****\n\n', async (t) => {
}
}

t.pass('***** Invokes and Queries complete *****');

try {
await installChaincode(t, client_org1, channel_org1, peer_org1, second_chaincode_name, second_chaincode_ver);
Expand Down Expand Up @@ -406,7 +416,7 @@ async function installChaincode(t, client, channel, peer, chaincode_id, chaincod
}

async function startChaincode(t, client, channel, orderer, peers, chaincode_id, chaincode_ver) {

t.pass('***** will start the chaincode ' + chaincode_id);
try {
// reset the testing
const tx_id = client.newTransactionID(true);
Expand Down Expand Up @@ -456,8 +466,10 @@ async function startChaincode(t, client, channel, orderer, peers, chaincode_id,
]
};

const proposal_results = await channel.sendInstantiateProposal(proposal_request, 10 * 60 * 1000);
const proposal_results = await channel.sendInstantiateProposal(proposal_request, 2 * 60 * 1000);
if (proposal_results[0][0].response.status === 200) {
t.pass('Successfully endorsed the sendInstantiateProposal');

const commit_request = {
orderer: orderer,
proposalResponses: proposal_results[0],
Expand All @@ -472,6 +484,8 @@ async function startChaincode(t, client, channel, orderer, peers, chaincode_id,
} else {
t.fail('Chaincode is not running');
}
} else {
t.fail('Failed to endorsed the sendInstantiateProposal');
}
} catch (error) {
logger.error(error);
Expand Down Expand Up @@ -519,7 +533,7 @@ async function createUpdateChannel(t, create, file, channel_name, client_org1, c
}
if (results.status === 'SUCCESS') {
t.pass('Successfully ' + text + ' the channel.');
await testUtil.sleep(5000);
await testUtil.sleep(20000);
} else {
t.fail('Failed to create the channel. ' + results.status + ' :: ' + results.info);
throw new Error('Failed to ' + text + ' the channel. ');
Expand Down Expand Up @@ -556,6 +570,7 @@ async function joinChannel(t, channel_name, peer, orderer, client) {
const join_results = await channel.joinChannel(request, 30000);
if (join_results && join_results[0] && join_results[0].response && join_results[0].response.status === 200) {
t.pass('Successfully joined channel on org');
await testUtil.sleep(5000);
} else {
t.fail('Failed to join channel on org');
throw new Error('Failed to join channel on org');
Expand Down
42 changes: 42 additions & 0 deletions test/typescript/integration/network-e2e/invoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,48 @@ test('\n\n***** Network End-to-end flow: specify endorsing peers *****\n\n', asy
t.end();
});

test('\n\n***** Network End-to-end flow: specify endorsing peers when discovery is enabled *****\n\n', async (t: any) => {
const gateway = new Gateway();
try {
const gatewayOptions = {
clientTlsIdentity: 'tlsId',
discovery: {
asLocalhost: false, // leave false so that if use a discovered peer is used it will fail
enabled: true,
},
identity: '[email protected]',
wallet: inMemoryWallet,
};

await gateway.connect(JSON.parse(ccp.toString()), gatewayOptions);
t.pass('Connected to the gateway');

const network = await gateway.getNetwork(channelName);
t.pass('Initialized the network, ' + channelName);

const contract = network.getContract(chaincodeId);
t.pass('Got the contract');

// these peers will not have the same names as the discovered peers or
// the same URL because asLocalhost is false
const channel = network.getChannel();
const endorsingPeer1 = channel.getChannelPeer('peer0.org1.example.com');
const endorsingPeer2 = channel.getChannelPeer('peer0.org2.example.com');

await contract.createTransaction('echo')
.setEndorsingPeers([endorsingPeer1, endorsingPeer2])
.submit('RESULT');
t.pass('Transaction was successfully submitted with endorsing peers');
} catch (error) {
const stacktrace = error.stack;
t.fail('Transaction failed with unexpected error: ' + stacktrace || error);
} finally {
gateway.disconnect();
}

t.end();
});

test('\n\n***** Network End-to-end flow: invoke transaction to move money using in memory wallet and no event strategy *****\n\n', async (t: any) => {
const gateway = new Gateway();

Expand Down
6 changes: 5 additions & 1 deletion test/typescript/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ const configOrg2: string = path.resolve(configPath, 'org2.yaml');
const channelName: string = 'mychannelts';

test('\n\n ** test TypeScript **', (t: any) => {
Client.setConfigSetting('initialize-with-discovery', false);

const client: Client = new Client();
t.equal(client.constructor.name, 'Client');

Expand Down Expand Up @@ -182,6 +184,7 @@ test('use the connection profile file', async (t: any) => {
}).then(() => {
t.pass('Successfully waited to make sure new channel was created.');
channel = client.getChannel(channelName);
t.comment (`Channel ${channelName} ::${channel.toString()}`);

const txId = client.newTransactionID(true);
const request: OrdererRequest = { txId };
Expand Down Expand Up @@ -241,6 +244,7 @@ test('use the connection profile file', async (t: any) => {
// set the material on the client to be used when building endpoints for the user
client.setTlsClientCertAndKey(cert, key);
channel = client.getChannel(channelName);
t.comment (`Channel ${channelName} ::${channel.toString()}`);

const txId: TransactionId = client.newTransactionID(true);
const request: JoinChannelRequest = {
Expand Down Expand Up @@ -733,7 +737,7 @@ test('use the connection profile file', async (t: any) => {
t.pass('Testing has completed successfully');
t.end();
}).catch((err: Error) => {
t.fail(err.message);
t.fail('Failed in test.ts - ' + err.stack);
t.end();
throw err;
});
Expand Down
25 changes: 20 additions & 5 deletions test/unit/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ module.exports.buildJoinEventMonitor = function(t, client, channel_name, peer_na
return event_block_promise;
};

module.exports.invokeAsAdmin = async function(t, client, channel, additional_request_opts) {
module.exports.invokeAsAdmin = async function(t, client, channel, additional_request_opts, shouldFail) {
let tx_id_string = null;
try {
// get a admin based transaction id
Expand All @@ -607,16 +607,25 @@ module.exports.invokeAsAdmin = async function(t, client, channel, additional_req
let one_good = false;
const proposal_response = proposalResponses[i];
if (proposal_response.response && proposal_response.response.status === 200) {
t.pass('transaction proposal has response status of good');
if (!shouldFail) {
t.pass('transaction proposal has response status of good');
}
one_good = true;
} else {
t.fail('transaction proposal was bad');
if (!shouldFail) {
t.fail('transaction proposal was bad');
} else {
t.pass('transaction proposal was bad');
}
}
all_good = all_good & one_good;
}

if (!all_good) {
t.fail('Failed to send invoke Proposal or receive valid response. Response null or status is not 200. exiting...');
if (!shouldFail) {
t.fail('Failed to send invoke Proposal or receive valid response. Response null or status is not 200. exiting...');
}
t.comment('###### got an error - will throw and error');
throw new Error('Failed to send invoke Proposal or receive valid response. Response null or status is not 200. exiting...');
}
request = {
Expand All @@ -637,7 +646,13 @@ module.exports.invokeAsAdmin = async function(t, client, channel, additional_req
}
} catch (error) {
logger.error('Invoke - catch network config test error:: %s', error.stack ? error.stack : error);
t.fail('Test failed with ' + error);
t.comment('###### got an error - ' + error);

if (!shouldFail) {
t.fail('Test failed with ' + error);
} else {
throw error;
}
}

return tx_id_string;
Expand Down

0 comments on commit b06fda4

Please sign in to comment.