Trying to run the Hyperledger calliper on my chaincode in test network and keep getting errors with create transaction - hyperledger

I am new to the block chain. Trying to run the calliper on my chaincode, in the the test network and getting the following errors. Not sure what I need to do here, to get the arguments be passed successfully to the chaincode.
Calliper command I used:
npx caliper launch manager --caliper-workspace ./ --caliper-networkconfig networks/networkConfig.yaml --caliper-benchconfig benchmarks/myPolicyBenchmark.yaml --caliper-flow-only-test --caliper-fabric-gateway-enabled
My Workload
'use strict';
const { WorkloadModuleBase } = require('#hyperledger/caliper-core');
class MyWorkload extends WorkloadModuleBase {
constructor() {
super();
}
async initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext) {
await super.initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext);
for ( let i=0; i<this.roundArguments.policies; i++) {
const policyID = `${this.workerIndex}_${i}`;
console.log(`Worker ${this.workerIndex}: Creating policy ${policyID}`);
const request = {
contractId: this.roundArguments.contractId,
contractFunction: 'CreatePolicy',
invokerIdentity: 'Admin',
contractAtguments: [policyID,"Test Policy 2","This is a test policy", "PUBLIC","PUBLIC","[\"READ\"]", "ABC", "abc#gmail.com", "[\"NONE\"]", "{}"],
readOnly: false
};
await this.sutAdapter.sendRequests(request);
}
}
async submitTransaction() {
const randomId = Math.floor(Math.random()*this.roundArguments.policies);
const myArgs = {
contractId: this.roundArguments.contractId,
contractFunction: 'ReadPolicy',
invokerIdentify: 'Admin',
//contractArguments: [`${this.workerIndex}_${randomId}`],
contractArguments: ['3'],
readOnly: true
};
await this.sutAdapter.sendRequests(myArgs);
}
async cleanupWorkloadModule() {
for (let i=0; i<this.roundArguments.policies; i++){
const policyID = `${this.workerIndex}_${i}`;
console.log(`Worker ${this.workerIndex}: Deleting policy ${policyID}`);
const request = {
contractId: this.roundArguments.contractId,
contractFunction: 'DeletePolicy',
invokerIdentity: 'Admin',
contractAtguments: [policyID],
readOnly: false
};
await this.sutAdapter.sendRequests(request);
}
}
}
function createWorkloadModule() {
return new MyWorkload();
}
module.exports.createWorkloadModule = createWorkloadModule;
The error I get is
2022.06.14-00:46:51.063 info [caliper] [caliper-worker] Info: worker 0 prepare test phase for round 0 is starting...
Worker 0: Creating policy 0_0
2022.06.14-00:46:51.078 info [caliper] [caliper-worker] Info: worker 1 prepare test phase for round 0 is starting...
Worker 1: Creating policy 1_0
2022-06-14T06:46:51.130Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
2022.06.14-00:46:51.132 error [caliper] [connectors/v2/FabricGateway] Failed to perform submit transaction [CreatePolicy] using arguments [], with error: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: Error: Expected 10 parameters, but 0 have been supplied
at newEndorsementError (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/fabric-network/lib/transaction.js:49:12)
at getResponsePayload (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/fabric-network/lib/transaction.js:17:23)
at Transaction.submit (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/fabric-network/lib/transaction.js:212:28)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async V2FabricGateway._submitOrEvaluateTransaction (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-fabric/lib/connector-versions/v2/FabricGateway.js:376:26)
at async V2FabricGateway._sendSingleRequest (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-fabric/lib/connector-versions/v2/FabricGateway.js:170:16)
at async V2FabricGateway.sendRequests (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-core/lib/common/core/connector-base.js:78:28)
at async MyWorkload.initializeWorkloadModule (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/workload/readPolicy.js:25:13)
at async CaliperWorker.prepareTest (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-core/lib/worker/caliper-worker.js:160:13)
at async WorkerMessageHandler._handlePrepareMessage (/Users/sam/my_thesis/Project/changetracker/caliper-workspace/node_modules/#hyperledger/caliper-core/lib/worker/worker-message-handler.js:210:13)
The same inputs works fine with running through the peer
peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile "${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem" -C mychannel -n policylist --peerAddresses localhost:7051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" --peerAddresses localhost:9051 --tlsRootCertFiles "${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt" -c '{"function":"CreatePolicy","Args":["4","Test Policy 2","This is a test policy", "PUBLIC","PUBLIC","[\"READ\"]", "ABC", "abc#gmail.com", "[\"NONE\"]", "{}" ]}'
2022-06-14 00:58:06.489 CST 0001 INFO [chaincodeCmd] chaincodeInvokeOrQuery -> Chaincode invoke successful. result: status:200 payload:"{\"PolicyId\":\"4\",\"docType\":\"PolicyDoc\",\"PolicyName\":\"Test Policy 2\",\"PolicyDescription\":\"This is a test policy\",\"PolicyDataClassification\":\"PUBLIC\",\"PolicyAccessCategory\":\"PUBLIC\",\"PolicyAccessMethod\":[\"READ\"],\"PolicyOwner\":\"ABC\",\"PolicyApprovalStatus\":\"NEW\",\"PolicyCreatedOn\":\"Tue, 14 Jun 2022 06:58:06 GMT\",\"PolicyContactEmail\":\"abc#gmail.com\",\"PolicyRestrictions\":\"[\\\"NONE\\\"]\",\"PolicyMiscellaneous\":{}}"

Related

Getting index out of range error when creating metaplex metadata account

Why am I getting the following error when trying to create a metadata account using createCreateMetadataAccountV2Instruction from the #metaplex-foundation/mpl-token-metadata library?
SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: Program failed to complete
at Connection.sendEncodedTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\connection.ts:4464:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Connection.sendRawTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\connection.ts:4423:20)
at async Connection.sendTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\connection.ts:4411:12)
at async sendAndConfirmTransaction (C:\xampp\htdocs\sol-tools\node_modules\#solana\web3.js\src\util\send-and-confirm-transaction.ts:31:21)
at async addMetadataToToken (C:\xampp\htdocs\sol-tools\src\lib\metadata.ts:86:16)
at async Command.<anonymous> (C:\xampp\htdocs\sol-tools\src\cli.ts:48:7) {
logs: [
'Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s invoke [1]',
'Program log: Instruction: Create Metadata Accounts v2',
"Program log: panicked at 'range end index 36 out of range for slice of length 0', program/src/utils.rs:231:27",
'Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s consumed 6223 of 1400000 compute units',
'Program failed to complete: BPF program panicked',
'Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s failed: Program failed to complete'
]
}
Here's my code:
import {
createCreateMetadataAccountV2Instruction,
PROGRAM_ID,
} from '#metaplex-foundation/mpl-token-metadata'
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
Transaction,
} from '#solana/web3.js'
export const addMetadataToToken = async (
connection: Connection,
tokenMint: PublicKey,
tokenOwner: Keypair,
name: string,
symbol: string,
arweaveLink: string
) => {
const seed1 = Buffer.from('metadata', 'utf8')
const seed2 = PROGRAM_ID.toBuffer()
const seed3 = tokenMint.toBuffer()
const [metadataPDA, _bump] = PublicKey.findProgramAddressSync(
[seed1, seed2, seed3],
PROGRAM_ID
)
const accounts = {
metadata: metadataPDA,
mint: tokenMint,
mintAuthority: tokenOwner.publicKey,
payer: tokenOwner.publicKey,
updateAuthority: tokenOwner.publicKey,
}
const dataV2 = {
name,
symbol,
uri: arweaveLink,
// we don't need these
sellerFeeBasisPoints: 0,
creators: null,
collection: null,
uses: null,
}
const args = {
createMetadataAccountArgsV2: {
data: dataV2,
isMutable: true,
},
}
const ix = createCreateMetadataAccountV2Instruction(accounts, args)
const tx = new Transaction()
tx.add(ix)
const txid = await sendAndConfirmTransaction(connection, tx, [tokenOwner])
console.log(txid)
}
Turns out I was on trying to create metadata for a token on devnet, but was using a mainnet-beta rpc endpoint for the Connection class. Thus the token I was trying to create metadata for didn't exist.
This is a really Common Error Message that occurs when there is some issue with what you are passing to the program. So make sure everything that you are input to the program is correct. In 90% of the cases, it gets resolved when checking the inputs correctly.

Hyperledger Fabric: Broadcast Client xxx is not connected

I use the following two sdk to connect and interact with the local-network created by the extension.
package.json:
...
"fabric-ca-client": "^2.2.0",
"fabric-network": "^2.2.0",
...
What I did first was get the default wallets created here:
C:\Users\johnny.dacosta\.fabric-vscode\environments\chaincode-env
I copied it to my workspace and then added the `admin' identity to my wallets with the following function:
if(this.walletProxy == null){
//get wallet store
this.walletProxy = await createWalletProxy(this.configService.get('localnetwork.orgWalletPath'));
//build new identity
const certBasePath = joinPathFromCWD(this.configService.get('localnetwork.pathIdentityCert'));
const keyBasePath = joinPathFromCWD(this.configService.get('localnetwork.pathIdentityKey'));
const certFilename = getFilesFromPath(certBasePath)[0];
const keyFilename = getFilesFromPath(keyBasePath)[0];
if(!certFilename || !keyFilename){
throw new NotFoundException("certFilename or keyFilename not found");
}
const cert = readFileSyncUTF8(`${certBasePath}/${certFilename}`).toString();
const key = readFileSyncUTF8(`${keyBasePath}/${keyFilename}`).toString();
//add new identity
await this.walletProxy.addIdentity(this.configService.get('localnetwork.identity'), {
credentials: {
certificate: cert,
privateKey: key,
},
mspId: 'Org1MSP',
type: 'X.509',
})
}
//ENV
{
orgWalletPath: ["local-network", "wallets", "Org1", "admin", "user"],
pathIdentityCert: ["local-network", "wallets", "Org1", "admin", "signcerts"],
pathIdentityKey: ["local-network", "wallets", "Org1", "admin", "keystore"],
}
I manage to add the new identity admin:
{"credentials":{"certificate":"-----BEGIN CERTIFICATE-----\nMIICWTCCAf+gAwIBAgIUIcgD17E4QtTsYMfeUO9Gg4SdSyIwCgYIKoZIzj0EAwIw\nfzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xHzAdBgNVBAoTFkludGVybmV0IFdpZGdldHMsIEluYy4xDDAK\nBgNVBAsTA1dXVzEUMBIGA1UEAxMLZXhhbXBsZS5jb20wHhcNMjAwODEzMTIwNjAw\nWhcNMjEwODEzMTIxMTAwWjBdMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGgg\nQ2Fyb2xpbmExFDASBgNVBAoTC0h5cGVybGVkZ2VyMQ8wDQYDVQQLEwZjbGllbnQx\nDjAMBgNVBAMTBWFkbWluMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfkO0UxnK\nfEKmESj0GxyjSh8ljFSgXOCFqINXo66hnBb8M5XQMNE4HJFrJ5Aa0bPfvlNjCLXp\nu4MGWN3mFf1qb6N7MHkwDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAwHQYD\nVR0OBBYEFO/aOEcikRVj/j/coHPhFPS74x4WMB8GA1UdIwQYMBaAFBdnQj2qnoI/\nxMUdn1vDmdG1nEgQMBkGA1UdEQQSMBCCDmRvY2tlci1kZXNrdG9wMAoGCCqGSM49\nBAMCA0gAMEUCIQC/inkjTud4btEeECODuZQhEEZG0OgDDoSkfhNNJF82wgIgYYvF\nLK1NgJxMdYwxQYhGXSV568d+HJROXgb7+vsjd3g=\n-----END CERTIFICATE-----\n","privateKey":"-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGRpFEGhHS95y2Fyr\nLk6s6gd0V5D61akQC4RkEC1xYzmhRANCAAR+Q7RTGcp8QqYRKPQbHKNKHyWMVKBc\n4IWog1ejrqGcFvwzldAw0TgckWsnkBrRs9++U2MItem7gwZY3eYV/Wpv\n-----END PRIVATE KEY-----\n"},"mspId":"Org1MSP","type":"X.509","version":1}
With this identity I can getState of my asset:
But if I try to do putState transaction I got this error:
2020-08-13T13:14:14.117Z - error: [DiscoveryHandler]: _build_endorse_group_member >> G1:0 - error on endorsement to peer0.org2.example.com:17097 error Error: Broadcast Client peer0.org2.example.com:17097 grpc://localhost:17097 is not connected
2020-08-13T13:14:14.118Z - error: [DiscoveryHandler]: _build_endorse_group_member >> G0:0 - error on endorsement to peer0.org1.example.com:17092 error Error: Broadcast Client peer0.org1.example.com:17092 grpc://localhost:17092 is not connected
[Nest] 22548 - 2020-08-13 3:14:14 PM [ExceptionsHandler] Cannot read property 'name' of undefined +747178ms
TypeError: Cannot read property 'name' of undefined
at newEndorsementError (C:\DEV\CIB\cib-ledger-api\node_modules\fabric-network\lib\transaction.js:33:36)
at getResponsePayload (C:\DEV\CIB\cib-ledger-api\node_modules\fabric-network\lib\transaction.js:17:23)
at Transaction.submit (C:\DEV\CIB\cib-ledger-api\node_modules\fabric-network\lib\transaction.js:214:28)
at process._tickCallback (internal/process/next_tick.js:68:7)
All the peer are up:
I'm just confused why is not working with putState transaction.
I already check my smartcontract is good I can manage to do putState operation with the extension:
Your Environment
IBM Blockchain Platform Extension Version: 1.0.36
Visual Studio Code version: 1.47.3
Environment name and version: Node.js v10.16.3, npm v6.14.7):
Operating System and version: Windows 10 Enterprise v1903
I got the problem...
Just before the transaction I disconnected from the network...
async submitTransaction(transactionConfig: ITransaction2HLF): Promise<void> {
console.log(transactionConfig.transactionName)
console.log(...transactionConfig.params)
await this.buildInstance(transactionConfig);
this.gateway.disconnect() // <-- ERROR
await this.contract.submitTransaction(transactionConfig.transactionName, ...transactionConfig.params);
this.gateway.disconnect()
}
I just removed the line and I downgrade the version 2.2 to 1.4.x due to the vscode extension ibm blockchain plateform requirements.

gRPC-node: When *Dockerizing* Service, request doesn't go through service's server? [Screenshots included]

I created a really simple bookstore with a Books, Customer, and a main service. This particular problem involves the main and books service.
I'm currently making a gRPC request called: "createBook", which creates a book in our DB, and also console logs.
When running the gRPC server (booksServer) without docker, the process runs smoothly.
But as soon as I use docker, it seems as if a gRPC request doesn't go into the gRPC server...
By "using docker" I mean using docker to run the booksServer. (As shown below)
Result: Without Docker
As you can see, without docker, the request is fulfilled, and everything works as it should.
Our gRPC client makes a call to the gRPC server (in which metadata is created) and the metadata is also sent back to the client.
(Scroll down to see the gRPC server file with the method called "getBooks".)
booksServer (without docker)
*** Notice the console logs in the booksServer!!! ***
Let me run the booksServer (with docker)
(Dockerfile below)
FROM node:12.14.0
WORKDIR /usr/src/app
COPY package*.json ./
COPY . /usr/src/app
RUN npm install
RUN npm install nodemon -g
EXPOSE 30043
CMD ["nodemon", "booksServer.js"
Here's my main service docker file too which initiates the request:
FROM node:12.14.0
WORKDIR /usr/src/app
COPY package*.json ./
COPY . /usr/src/app
# COPY wait-for-it.sh .
# RUN chmod +x /wait-for-it.sh
RUN npm install
EXPOSE 4555
CMD ["node", "main.js"]
^^^ Notice how when dockerfile is used to run booksServer
it doesn't go/run inside the booksServer file
***It does NOT produce any console.logs when I fire off a gRPC requesst***
This is what the booksServer.js file looks like
Heres the Books Stub
//use this for bookInitiator
const path = require('path');
const PROTO_PATH = path.join(__dirname, "../protos/books.proto");
const grpc = require("grpc");
const protoLoader = require("#grpc/proto-loader");
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
arrays: true
});
const BooksService = grpc.loadPackageDefinition(packageDefinition).BooksService;
// potential issues to fix 1) making localhost port dynamic 2) docker containerization may cause conflict
const client = new BooksService (
"172.17.0.2:30043",
grpc.credentials.createInsecure()
);
console.log("Creating stub inside booksStub");
module.exports = client;
Here's the gRPC Server file (with the binded ports).
// const PROTO_PATH = "../protos/books.proto";
const path = require('path');
const PROTO_PATH = path.join(__dirname, './protos/books.proto');
const grpc = require("grpc");
const protoLoader = require("#grpc/proto-loader");
const express = require("express");
const controller = require("./booksController.js");
const app = express();
app.use(express.json());
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
arrays: true,
});
const booksProto = grpc.loadPackageDefinition(packageDefinition);
const { v4: uuidv4 } = require("uuid");
const server = new grpc.Server();
server.addService(booksProto.BooksService.service, {
CreateBook: (call, callback) => {
console.log("call to CreateBook");
//sample will take the call information from the client(stub)
const book = {
title: call.request.title,
author: call.request.author,
numberOfPages: call.request.numberOfPages,
publisher: call.request.publisher,
id: call.request.id,
};
controller.createBook(book);
let meta = new grpc.Metadata();
meta.add("response", "none");
console.log("metadata in createBook...: ", meta);
call.sendMetadata(meta);
callback(
null,
//bookmodel.create
{
title: `completed for: ${call.request.title}`,
author: `completed for: ${call.request.author}`,
numberOfPages: `completed for: ${call.request.numberOfPages}`,
publisher: `completed for: ${call.request.publisher}`,
id: `completed for: ${call.request.id}`,
}
);
},
GetBooks: (call, callback) => {
console.log("call to GetBooks");
// read from database
let meta = new grpc.Metadata();
meta.add('response', 'none');
call.sendMetadata(meta);
controller.getBooks(callback);
}
});
server.bind("0.0.0.0:30043", grpc.ServerCredentials.createInsecure());
console.log("booksServer.js running at 0.0.0.0:30043");
console.log("Inside Books Server!");
console.log("call from books server");
server.start();
horus.js (custom made simple tracing tool),
grab trace grabs the journey of a certain request
and sends it back to the gRPC client as metadata
const fs = require("fs");
const grpc = require("grpc");
const path = require("path");
class horus {
constructor(name) {
this.serviceName = name; // represents the name of the microservices
this.startTime = null;
this.endTime = null;
this.request = {};
this.targetService = null; // represents the location to which the request was made
this.allRequests = []; // array which stores all requests
this.timeCompleted = null;
this.call;
}
static getReqId() {
// primitive value - number of millisecond since midnight January 1, 1970 UTC
// add service name/ initials to the beginning of reqId?
return new Date().valueOf();
}
// start should be invoked before the request is made
// start begins the timer and initializes the request as pending
start(targetService, call) {
this.startTime = Number(process.hrtime.bigint());
this.request[targetService] = "pending"; // {books: 'pending', responseTime: 'pending'}
this.request.responseTime = "pending";
this.targetService = targetService;
this.call = call;
this.request.requestId = horus.getReqId();
}
// end should be invoked when the request has returned
end() {
this.endTime = Number(process.hrtime.bigint());
this.request.responseTime = (
(this.endTime - this.startTime) /
1000000
).toFixed(3); //converting into ms.
this.sendResponse();
this.request.timeCompleted = this.getCurrentTime();
}
// grabTrace accepts inserts trace into request
// trace represents the "journey" of the request
// trace expects metaData to be 'none when the server made no additional requests
// trace expects metaData to be the request object generated by the server otherwise
// in gRPC, the trace must be sent back as meta data. objects should be converted with JSON.parse
grabTrace(metaData) {
//console.log("incoming meta data ", metaData);
console.log("Inside Grab Trace Method.");
console.log("Metadata inside grabTrace: ", metaData);
if (metaData === "none" || metaData === undefined) this.request[this.targetService] = "none";
else {
metaData = JSON.parse(metaData);
this.request[this.targetService] = metaData;
}
this.allRequests.push(this.request);
this.sendResponse();
}
// displayRequests logs to the console all stored requests
// setTimeout builds in deliberate latency since metadata may be sent before or after a request is done processing
displayRequests() {
console.log("\n\n");
console.log("Logging all requests from : ", this.serviceName);
this.allRequests.forEach((request) => {
console.log("\n");
console.log(request);
});
console.log("\n\n");
}
// sends response via metadata if service is in the middle of a chain
sendResponse() {
if (
this.request.responseTime === "pending" ||
this.request[this.targetService] === "pending" ||
this.call === undefined
)
return;
console.log("Inside send response");
let meta = new grpc.Metadata();
meta.add("response", JSON.stringify(this.request));
console.log('meta in send response: ', meta)
this.call.sendMetadata(meta);
}
writeToFile() {
console.log("call to writeToFile");
console.log("logging request obj ", this.request);
let strRequests = "";
for (let req of this.allRequests) {
// First write to file - contains Total
// subsequent - chained requests
strRequests += `Request ID: ${req.requestId}\n`;
strRequests += `"${
Object.keys(req)[0]
}" service -> Response received in ${Object.values(req)[1]} ms (Total)\n`;
strRequests += `Timestamp: ${req.timeCompleted}\n`;
// while we don't hit an empty object on the 1st key, go inside
// add numbering in order for nested requests inside original?!
let innerObj = Object.values(req)[0];
while (innerObj !== "none") {
strRequests += `"${
Object.keys(innerObj)[0]
}" service -> Response received in ${Object.values(innerObj)[1]} ms\n`;
strRequests += `Timestamp: ${innerObj.timeCompleted}\n`;
innerObj = Object.values(innerObj)[0];
}
strRequests +=
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
}
console.log('strRequests', strRequests)
fs.writeFile(this.serviceName + 'data' + '.txt', strRequests, { flag: "a+" }, (err) => {
if (err) {
console.error(err);
}
}); //'a+' is append mode
}
module.exports = horus;
main.js (initiates gRPC client request)
const path = require('path');
// const grpc = require("grpc");
const customersStub = require("./stubs/customersStub.js");
const booksStub = require("./stubs/booksStub.js");
const horusTracer = require(path.join(__dirname, "./horus/horus.js"));
//In master branch
console.log("Stub is Inside main service!!!");
const book = {
title: "ITttttt",
author: "Stephen King",
numberOfPages: 666,
publisher: "Random House",
id: 200,
};
const bookId = {
id: 200
}
const customer = {
id: 123,
name: "Lily",
age: 23,
address: "Blablabla",
favBookId: 100
};
const customerId = {
id: 123
}
let ht = new horusTracer("main");
function CreateBook () {
ht.start('books')
booksStub.CreateBook(book, (error, response) => {
if (error) console.log("there was an error ", error);
ht.end();
ht.displayRequests();
ht.writeToFile();
}).on('metadata', (metadata) => {
console.log("Before grab trace is invoked!");
ht.grabTrace(metadata.get('response')[0]);
});
}
}
CreateBook(); //Works
What I think is the issue.
Edit: murgatroid99 mentioned that it was a networking issue with docker!
~~~~~~~~~
I initially thought this was a networking issue, but I don't think it is
because all my docker files are running on the default bridge network.
So they all technically can communicate with one another...
Is it something wrong with nodemon interacting with Docker?
Does the server not output the console logs...?
Is the server actually running and working...?
Do I need a reverse proxy like nginx?
``
The problem is that your server is binding to "127.0.0.1:30043". You say that you are running the docker images using the default bridge network. In that mode the docker image has a different (virtual) network than the host machine has, so its loopback address is different from the host machine's loopback address. To fix that, you can instead bind the server to 0.0.0.0:30043 or [::]:30043to bind to other network interfaces that the client can connect to from outside of the docker container.
For the same reason, connecting the client to localhost:30043 will not work: its "localhost" address also refers to the loopback interface within the docker container. You should instead replace "localhost" with the IP address of the server container.
Alternatively, as described in this question, you can network the docker containers in "host" mode so that they share the same network with the host machine.

Cannot connect to Solace Cloud

I am following the solace tutorial for Publish/Subscribe (link: https://dev.solace.com/samples/solace-samples-java/publish-subscribe/). Therefore, there shouldn't be anything "wrong" with the code.
I am trying to get my TopicSubscriber to connect to the cloud. After building my jar I run the following command:
java -cp target/SOM_Enrichment-1.0-SNAPSHOT.jar TopicSubscriber <host:port> <client-username#message-vpn> <password>
(with the appropriate fields filled in)
I get the following error:
TopicSubscriber initializing...
Jul 12, 2018 2:27:56 PM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call
INFO: Connecting to host 'blocked out' (host 1 of 1, smfclient 2, attempt 1 of 1, this_host_attempt: 1 of 1)
Jul 12, 2018 2:28:17 PM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call
INFO: Connection attempt failed to host 'blocked out' ConnectException com.solacesystems.jcsmp.JCSMPTransportException: ('blocked out') - Error communicating with the router. cause: java.net.ConnectException: Connection timed out: no further information ((Client name: 'blocked out' Local port: -1 Remote addr: 'blocked out') - )
Jul 12, 2018 2:28:20 PM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel close
INFO: Channel Closed (smfclient 2)
Exception in thread "main" com.solacesystems.jcsmp.JCSMPTransportException" (Client name: 'blocked out' Local port: -1 Remote addr: 'blocked out') - Error communicating with the router.
Below is the TopicSubscriber.java file:
import java.util.concurrent.CountDownLatch;
import com.solacesystems.jcsmp.BytesXMLMessage;
import com.solacesystems.jcsmp.JCSMPException;
import com.solacesystems.jcsmp.JCSMPFactory;
import com.solacesystems.jcsmp.JCSMPProperties;
import com.solacesystems.jcsmp.JCSMPSession;
import com.solacesystems.jcsmp.TextMessage;
import com.solacesystems.jcsmp.Topic;
import com.solacesystems.jcsmp.XMLMessageConsumer;
import com.solacesystems.jcsmp.XMLMessageListener;
public class TopicSubscriber {
public static void main(String... args) throws JCSMPException {
// Check command line arguments
if (args.length != 3 || args[1].split("#").length != 2) {
System.out.println("Usage: TopicSubscriber <host:port> <client-username#message-vpn> <client-password>");
System.out.println();
System.exit(-1);
}
if (args[1].split("#")[0].isEmpty()) {
System.out.println("No client-username entered");
System.out.println();
System.exit(-1);
}
if (args[1].split("#")[1].isEmpty()) {
System.out.println("No message-vpn entered");
System.out.println();
System.exit(-1);
}
System.out.println("TopicSubscriber initializing...");
final JCSMPProperties properties = new JCSMPProperties();
properties.setProperty(JCSMPProperties.HOST, args[0]); // host:port
properties.setProperty(JCSMPProperties.USERNAME, args[1].split("#")[0]); // client-username
properties.setProperty(JCSMPProperties.PASSWORD, args[2]); // client-password
properties.setProperty(JCSMPProperties.VPN_NAME, args[1].split("#")[1]); // message-vpn
final Topic topic = JCSMPFactory.onlyInstance().createTopic("tutorial/topic");
final JCSMPSession session = JCSMPFactory.onlyInstance().createSession(properties);
session.connect();
final CountDownLatch latch = new CountDownLatch(1); // used for
// synchronizing b/w threads
/** Anonymous inner-class for MessageListener
* This demonstrates the async threaded message callback */
final XMLMessageConsumer cons = session.getMessageConsumer(new XMLMessageListener() {
#Override
public void onReceive(BytesXMLMessage msg) {
if (msg instanceof TextMessage) {
System.out.printf("TextMessage received: '%s'%n",
((TextMessage) msg).getText());
} else {
System.out.println("Message received.");
}
System.out.printf("Message Dump:%n%s%n", msg.dump());
latch.countDown(); // unblock main thread
}
#Override
public void onException(JCSMPException e) {
System.out.printf("Consumer received exception: %s%n", e);
latch.countDown(); // unblock main thread
}
});
session.addSubscription(topic);
System.out.println("Connected. Awaiting message...");
cons.start();
// Consume-only session is now hooked up and running!
try {
latch.await(); // block here until message received, and latch will flip
} catch (InterruptedException e) {
System.out.println("I was awoken while waiting");
}
// Close consumer
cons.close();
System.out.println("Exiting.");
session.closeSession();
}
}
Any help would be greatly appreciated.
java.net.ConnectException: Connection timed out
The log entry indicates that network connectivity to the specified DNS name/IP address cannot be established.
Next step includes:
Verifying that you are able to resolve the DNS name to an IP
address.
Verifying that the correct DNS name/IP address/Port is in use - You need the "SMF Host" in the Solace Cloud Connection Details.
Verifying that the IP address/Port is not blocked by an intermediate network device.

Appium with MochaJS "Not JSON response" when trying to run a test for iOS

I've tried the troubleshooting steps listed at http://appium.io/slate/en/1.5.3/?javascript#ios, but with no luck.
I run my test with:
$ mocha sample.js
This successfully installs the app on the device and opens it, but the test fails at the first step every time with this error:
Error: [elementByName("Username")] Not JSON response
at exports.newError (node_modules/wd/lib/utils.js:145:13)
at node_modules/wd/lib/callbacks.js:59:17
at node_modules/wd/lib/webdriver.js:179:5
at Request._callback (node_modules/wd/lib/http-utils.js:88:7)
at Request.self.callback (node_modules/request/request.js:187:22)
at Request.<anonymous> (node_modules/request/request.js:1048:10)
at IncomingMessage.<anonymous> (node_modules/request/request.js:969:12)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Here is my test:
//example from built.io
"use strict";
require("./helpers/setup");
require('colors');
var wd = require("wd"),
_ = require('underscore'),
Q = require('q'),
serverConfigs = require('./helpers/appium-servers');
var serverConfig = serverConfigs.local;
var driver = wd.promiseChainRemote(serverConfig);
var pry = require('pryjs');
var _p = require('./helpers/promise-utils'); // needed?
var simulator = false
var chai = require("chai");
// var assert = require('assert'); //needed?
var assert = chai.assert;
// var config = require('./helpers/config')
chai.config.includeStack = true;
describe("Node Sample Automation Code", function() {
this.timeout(300000);
var allPassed = true;
before(function() {
var serverConfig = process.env.SAUCE ? serverConfigs.sauce : serverConfigs.local;
var driver = wd.promiseChainRemote(serverConfig);
require("./helpers/logging").configure(driver);
var desired = _.clone(require("./helpers/caps").mycapabilities);
desired.app = require("./helpers/apps").myTestApp;
if (process.env.SAUCE) {
desired.name = 'Automation Code';
desired.tags = ['sample'];
}
return driver.init(desired);
});
after(function() {
return driver
.sleep(3000).quit().finally(function() {
if (process.env.SAUCE) {
return driver.sauceJobStatus(allPassed);
}
});
});
afterEach(function() {
allPassed = allPassed && this.currentTest.state === 'passed';
});
it("Should Login", function() {
return driver
.elementByName('Username').click()
//same field - this doesn't work either
// .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIATextField[1]")
});
});
I have the exact same error with the elementByXPath command, which uses the exact path to the element revealed by the Appium Inspector. In both cases I am using the commands exactly as in examples of other tests that work in other setups (also iOS and mocha), leading me to believe it's not my usage of the command, but something fundamentally wrong with communication between the device and Appium.
Here's an excerpt of the Appium Log that seems applicable to the error:
2016-12-26 03:47:43:217 - [MJSONWP] Responding to client with driver.getStatus() result: {"build":{"version":"1.5.3"...
2016-12-26 03:47:43:233 - [HTTP] --> POST /wd/hub/session/element {"using":"name","value":"Username"}
2016-12-26 03:47:43:237 - [debug] [HTTP] No route found. Setting content type to 'text/plain'
2016-12-26 03:47:43:239 - [HTTP] <-- POST /wd/hub/session/element 404 5 ms - 65
2016-12-26 03:47:43:242 - [MJSONWP] Responding to client with driver.getStatus() result: {"build":{"version":"1.5.3"...
I'd appreciate any help anyone can provide, even guesses or hints as to what the error "Not JSON response" means, and why that might be occurring. Thanks in advance.
I was defining driver twice - after commenting it out in the "before" block, and using the XPath command instead of .elementByName, it worked.

Resources