Implement custom VSCC to validate on basis of ChaincodeProposalPayload - hyperledger-fabric

I am trying to implement custom VSCC (Validation System Chaincode) to add some extra logic on the basis of FunctionName and and the payload data(ChaincodeProposalPayload) . Currently i am able to fetch ChaincodeProposalPayload from ChaincodeActionPayload but the data seems to be encoded.
Following is the code i am using.
// args[0] - function name (not used now)
// args[1] - serialized Envelope
// args[2] - serialized policy
args := stub.GetArgs()
// get the envelope...
env, err := utils.GetEnvelopeFromBlock(args[1])
if err != nil {
logger.Errorf("VSCC error: GetEnvelope failed, err %s", err)
return shim.Error(err.Error())
}
// ...and the payload...
payl, err := utils.GetPayload(env)
if err != nil {
logger.Errorf("VSCC error: GetPayload failed, err %s", err)
return shim.Error(err.Error())
}
// ...and the transaction...
tx, err := utils.GetTransaction(payl.Data)
if err != nil {
logger.Errorf("VSCC error: GetTransaction failed, err %s", err)
return shim.Error(err.Error())
}
// loop through each of the actions within
fmt.Println(len(tx.Actions))
for _, act := range tx.Actions {
cap, err := utils.GetChaincodeActionPayload(act.Payload)
if err != nil {
logger.Errorf("VSCC error: GetChaincodeActionPayload failed, err %s", err)
return shim.Error(err.Error())
}
fmt.Println("payload " + string(cap.ChaincodeProposalPayload))
}
In the console Payload is printed as encoded string like
mycc
invoke
a
b
10
How can i properly decode the payload into json?

Something like this should work:
// ChaincodeProposalPayload
cpp, err := utils.GetChaincodeProposalPayload(cap.ChaincodeProposalPayload)
if err != nil {
logger.Errorf("GetChaincodeProposalPayload failed: %s", err)
return shim.Error(err.Error())
}
// ChaincodeInvocationSpec
cis := &peer.ChaincodeInvocationSpec{}
err = proto.Unmarshal(cpp.Input, cis)
if err != nil {
logger.Errorf("GetChaincodeInvokeSpec failed: %s", err)
return shim.Error(err.Error())
}
spec := &peer.ChaincodeSpec
err = proto.Unmarshal(cis.GetChaincodeSpec(),spec)
if err != nil {
logger.Errorf("Unmarshal ChaincodeSpec failed: %s", err)
return shim.Error(err.Error())
}
ccName := spec.GetChaincodeId().GetName()
ccArgs := spec.GetInput().GetArgs()
fnName := ccArgs[0]
for _, arg := range ccArgs[1:] {
// do what you want with your args
}

Related

go - copy relative folder using embed

I am using our go library (it could be changed if necessary) with a folder named "devops", which contains nested content.
in the library, I copy the devops folder with his content, to another folder.
this is the copy function:
func CopyDirectory(scrDir, dest string) error { // scrDir = devops
entries, err := ioutil.ReadDir(scrDir)
if err != nil {
return err
}
for _, entry := range entries {
sourcePath := filepath.Join(scrDir, entry.Name())
destPath := filepath.Join(dest, entry.Name())
fileInfo, err := os.Stat(sourcePath)
fmt.Println(fileInfo)
if err != nil {
return err
}
stat, ok := fileInfo.Sys().(*syscall.Stat_t)
if !ok {
return fmt.Errorf("failed to get raw syscall.Stat_t data for '%s'", sourcePath)
}
switch fileInfo.Mode() & os.ModeType {
case os.ModeDir:
if err := CreateIfNotExists(destPath, 0755); err != nil { // CreateIfNotExists is a internal function
return err
}
if err := CopyDirectory(sourcePath, destPath); err != nil { // CopyDirectory is a internal function
return err
}
case os.ModeSymlink:
if err := CopySymLink(sourcePath, destPath); err != nil { // CopySymLink is a internal function
return err
}
default:
if err := Copy(sourcePath, destPath); err != nil { // Copy is a internal function
return err
}
}
if err := os.Lchown(destPath, int(stat.Uid), int(stat.Gid)); err != nil {
return err
}
isSymlink := entry.Mode()&os.ModeSymlink != 0
if !isSymlink {
if err := os.Chmod(destPath, entry.Mode()); err != nil {
return err
}
}
}
return nil
}
the library runs well as self-running, but when I use it from another project, it tries to copy the devops folder from the project path, and of course, fails.
I tried doing it with embed pkg, but the code fails when calling
fileInfo.Sys().(*syscall.Stat_t)
with an error that doesn't give any details.
this is the my code:
//go:embed devops
var f embed.FS
...
dir, _ := f.ReadDir("devops")
for _, entry := range dir {
fileInfo, _ := entry.Info()
err, ok := fileInfo.Sys().(*syscall.Stat_t)
if !ok {
println(err) // prints 0x0
}
}
How to solve it?
P.S. the code runs in Linux OS.

Fabric-sdk-go How to create the client context using msp CAclient

i am trying to use the hyperledger go sdk by importing on
of the module
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/msp .
I want to create the CA client instance by using hyperledger fabric go-sdk, which module do i need to import and how to do it, could anyone please suggest?
I am using below cmd to generate the fabric server CA client config file.
./bin/fabric-ca-client enroll admin:adminpws localhost:7054
Below is the code, which create the fabric sdk context, using the fabric-ca-client.yaml file which is generated by using the above cmd. if i am doing anything wrong let me know.
package main
import (
"fmt"
"net"
"os"
"path/filepath"
"strings"
clientmsp "github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
mspid "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/core/cryptosuite"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
"github.com/hyperledger/fabric-sdk-go/pkg/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/msp/test/mockmsp"
)
var (DefaultHome = os.ExpandEnv("$PWD/CONFIG"))
var caServerURL string
var caServer = &mockmsp.MockFabricCAServer{}
const (
caServerURLListen = "http://localhost:7054"
configFile = "fabric-ca-server-config.yaml"
)
type nwConfig struct {
CertificateAuthorities map[string]msp.CAConfig
}
type clientFixture struct {
cryptoSuiteConfig core.CryptoSuiteConfig
identityConfig mspid.IdentityConfig
}
func main() {
// Initiate the sdk using the config file
client := clientFixture{}
sdk := client.setup()
//create the CA instance
c, err := clientmsp.New(sdk.Context())
if err != nil {
fmt.Println("failed to create msp client", err)
return
}
fmt.Println("New client instance created", c)
}
func (f *clientFixture) setup() *fabsdk.FabricSDK {
var lis net.Listener
var err error
if !caServer.Running() {
lis, err = net.Listen("tcp", strings.TrimPrefix(caServerURLListen,
"http://"))
if err != nil {
panic(fmt.Sprintf("Error starting CA Server %s", err))
}
caServerURL = "http://" + lis.Addr().String()
}
configPath := filepath.Join(DefaultHome, configFile)
backend, err := config.FromFile(configPath)()
if err != nil {
fmt.Println(err)
}
configProvider := func() ([]core.ConfigBackend, error) {
return backend, nil
}
// Instantiate the SDK
sdk, err := fabsdk.New(configProvider)
if err != nil {
fmt.Println(err)
}
configBackend, err := sdk.Config()
if err != nil {
panic(fmt.Sprintf("Failed to get config: %s", err))
}
f.cryptoSuiteConfig = cryptosuite.ConfigFromBackend(configBackend)
f.identityConfig, _ = msp.ConfigFromBackend(configBackend)
if err != nil {
fmt.Println(err)
}
ctxProvider := sdk.Context()
ctx, err := ctxProvider()
if err != nil {
fmt.Println(err)
}
// Start Http Server if it's not running
if !caServer.Running() {
caServer.Start(lis, ctx.CryptoSuite())
}
return sdk
}
import mspclient
mspclient "github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
mspClient, err := mspclient.New(
*fabsdk.FabricSDK.Context(),
mspclient.WithOrg(OrgName),
)
if err != nil {
return mspClient, errors.WithMessage(err, "failed to create MSP client")
}
After that you can use below services
err = mspClient.Enroll("Admin#org1",
msp.WithSecret("Admin#org1"),
msp.WithProfile("tls"),
)
if err != nil {
return errors.WithMessage(err, "failed to register identity")
}

Cannot associate an asset with blob

I am trying to upload a video to azure media services, but once i create the asset and then upload the video to blob with the SAS url, the asset does not contain the video.
main.go
func main() {
assetName := "sample1"
asset, err := azureMedia.CreateAsset(assetName)
if err != nil {
panic(err)
}
log.Println("Asset Name: ", *asset.Name)
sasURL, err := azureMedia.GetStorageURLForAsset(assetName)
if err != nil {
panic(err)
}
log.Println(sasURL)
err = storage.UploadToBlobFromSASUrl(sasURL)
if err != nil {
panic(err)
}
return
}
media_services.go
func CreateAsset(assetName string) (*media.Asset, error) {
asset, err := assetsClient.CreateOrUpdate(context.Background(), resourceGroupName, accountName, assetName, media.Asset{})
if err != nil {
panic(err)
}
return &asset, nil
}
func GetStorageURLForAsset(assetName string) (string, error) {
result, err := assetsClient.ListContainerSas(context.Background(), resourceGroupName, accountName, assetName, media.ListContainerSasInput{
ExpiryTime: &date.Time{Time: time.Now().Add(time.Hour * 4).UTC()},
Permissions: media.ReadWrite,
})
if err != nil {
panic(err)
}
return (*result.AssetContainerSasUrls)[0], nil
}
storage.go
func UploadToBlobFromSASUrl(sasUrl string) error {
// When someone receives the URL, they access the SAS-protected resource with code like this:
u, err := url.Parse(sasUrl)
if err != nil {
panic(err)
}
containerURL := azblob.NewContainerURL(*u, azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{}))
blockBlobUrl := containerURL.NewBlockBlobURL("sample.mp4")
video, err := os.Open("./sample_videos/sample1.mp4")
if err != nil {
panic(err)
}
resp, err := blockBlobUrl.Upload(context.Background(), video, azblob.BlobHTTPHeaders{}, azblob.Metadata{}, azblob.BlobAccessConditions{})
if err != nil {
panic(err)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Response().Body)
if err != nil {
panic(err)
}
newStr := buf.String()
log.Println(resp.Status(), resp.StatusCode(), newStr)
return nil
}
From what i understood from the docs, the asset should be present and be associated with the video blob, but when i tried to encode it, it says there is no file associated with the asset.
Is there something I'm missing? Any help is appreciated

Getting "runtime error: invalid memory address or nil pointer dereference" when querying the chaincode

I'm using fabric-sdk-go to install, instantiate, invoke and querying the chaincode.
chaincode installation is successful.
root#991bc7577959:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer chaincode list --installed
Get installed chaincodes on peer:
Name: myproject, Version: 1.0, Path: github.com/hyperledger/myproject/chaincode/, Id: 130607a18ab3fe332854d7c2048f04b89e3c740e1ffa97c76c9ced266e6714ca
chaincode instantiation.
Snippet of code
ccPolicy := cauthdsl.SignedByAnyMember([]string{"Seller", "Buyer"})
fmt.Println("Value of ccPolicy is: ", ccPolicy)
resp, err := setup.admin.InstantiateCC(setup.ChannelID,
resmgmt.InstantiateCCRequest{
Name: setup.ChainCodeID,
Path: setup.ChaincodeGoPath,
Version: "1.0",
Args: [][]byte{[]byte("init"), []byte("Seller"), []byte("100"), []byte("Buyer"), []byte("200")},
Policy: ccPolicy,
})
checking the docker container
root#991bc7577959:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer chaincode list --instantiated -C mychannel
Get instantiated chaincodes on channel mychannel:
Name: myproject, Version: 1.0, Path: github.com/hyperledger/myproject/chaincode/, Input: <nil>, Escc: escc, Vscc: vscc
Here the chaincode is instantiated but the Input tag is showing nil value. Is it expected? Isn't it suppose to show the values that I've used for instantiation
Querying the chaincode
snippet of code
func (setup *FabricSetup) Query(OrgName string) (string, error) {
fmt.Println("\n Calling query method")
// Prepare arguments
var args []string
args = append(args, OrgName)
response, err := setup.client.Query(channel.Request{
ChaincodeID: setup.ChainCodeID,
Fcn: "invoke",
Args: [][]byte{[]byte("query"), []byte(args[0])}})
if err != nil {
return "", fmt.Errorf("failed to query: %v", err)
}
fmt.Println("\n Query chaincode ended")
return string(response.Payload), err
}
this querying of chaincode is resulting in below error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x9e17e0]
goroutine 1 [running]:
github.com/hyperledger/fabric-sdk-go/pkg/client/channel.(*Client).Query(0x0, 0xdb43d4, 0x9, 0xdb14ef, 0x6, 0xc00016ff80, 0x2, 0x2, 0x0, 0x0, ...)
/home/alpha/GoWorkspace/src/github.com/hyperledger/fabric-sdk-go/pkg/client/channel/chclient.go:97 +0xc0
github.com/hyperledger/myproject/sdk.(*FabricSetup).Query(0xc000179ea8, 0xdb0f3d, 0x6, 0x0, 0xdbbe50, 0x13, 0xdb43cb) >/home/alpha/GoWorkspace/src/github.com/hyperledger/myproject/sdk/query.go:17 +0x2d4
main.main()
/c/Projects/Go/src/github.com/hyperledger/myproject/main.go:79 +0x176
setup.go: file for creating a channel, installing and instantiating chaincode
import packages
type FabricSetup struct {
ConfigFile string
OrgID string
OrdererID string
ChannelID string
ChainCodeID string
initialized bool
ChannelConfig string
ChaincodeGoPath string
ChaincodePath string
OrgAdmin string
OrgName string
UserName string
client *channel.Client
admin *resmgmt.Client
adminIdentity *msp.SigningIdentity
sdk *fabsdk.FabricSDK
event *event.Client
}
// Initialize reads the configuration file and sets up the client, chain and event hub
func (setup *FabricSetup) Initialize() error {
// Step 1: creates the channel and updates all of the anchor peers for all orgs
identityManagerClientContext := setup.sdk.Context(fabsdk.WithUser(setup.OrgAdmin), fabsdk.WithOrg(setup.OrgName))
if err != nil {
return errors.WithMessage(err, "failed to load Admin identity")
}
fmt.Printf("\n Step 2.a: Value of identityManagerClientContext is: ", identityManagerClientContext)
// Channel management client is responsible for managing channels (create/update channel)
chMgmtClient, err := resmgmt.New(identityManagerClientContext)
if err != nil {
return errors.WithMessage(err, "failed to create channel management client from Admin identity")
}
setup.admin = chMgmtClient
mspClient, err := mspclient.New(setup.sdk.Context(), mspclient.WithOrg(setup.OrgName))
if err != nil {
return errors.WithMessage(err, "failed to create MSP client")
}
adminIdentity, err := mspClient.GetSigningIdentity(setup.OrgAdmin)
if err != nil {
return errors.WithMessage(err, "failed to get admin signing identity")
}
setup.adminIdentity = &adminIdentity
fmt.Println("Initialization Successful")
setup.initialized = true
return nil
}
// CreateChannel for creating channel between the Organizations
func (setup *FabricSetup) CreateChannel() error {
req := resmgmt.SaveChannelRequest{
ChannelID: setup.ChannelID,
ChannelConfigPath: setup.ChannelConfig,
SigningIdentities: []msp.SigningIdentity{*setup.adminIdentity},
}
txID, err := setup.admin.SaveChannel(req, resmgmt.WithOrdererEndpoint(setup.OrdererID))
if err != nil || txID.TransactionID == "" {
return errors.WithMessage(err, "failed to save channel")
}
fmt.Println("Channel created")
return nil
}
// joins all peers in all of the given orgs to the given channel
func (setup *FabricSetup) JoinChannel() error {
// Make admin user join the previously created channel
if err := setup.admin.JoinChannel(
setup.ChannelID,
resmgmt.WithRetry(retry.DefaultResMgmtOpts),
resmgmt.WithOrdererEndpoint(setup.OrdererID)); err != nil {
return errors.WithMessage(err, "failed to make admin join channel")
}
fmt.Println("Channel joined")
return nil
}
// InstallCC to install and instantiate the chaincode
func (setup *FabricSetup) InstallCC() error {
// Create the chaincode package that will be sent to the peers
ccPkg, err := packager.NewCCPackage(setup.ChaincodePath, setup.ChaincodeGoPath)
if err != nil {
return errors.WithMessage(err, "failed to create chaincode package")
}
fmt.Println("ccPkg created")
// Install example cc to org peers
installCCReq := resmgmt.InstallCCRequest{
Name: setup.ChainCodeID,
Path: setup.ChaincodePath,
Version: "1.0", //chaincode version. first version of chaincode
Package: ccPkg,
}
_, err = setup.admin.InstallCC(installCCReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts))
if err != nil {
return errors.WithMessage(err, "failed to install chaincode")
}
fmt.Println("Chaincode installed")
return nil
}
// InstantiateCC for instantiating the chaincode
func (setup *FabricSetup) InstantiateCC() error {
// Set up chaincode policy
ccPolicy := cauthdsl.SignedByAnyMember([]string{"Seller", "Buyer"})
fmt.Println("Value of ccPolicy is: ", ccPolicy)
resp, err := setup.admin.InstantiateCC(setup.ChannelID, resmgmt.InstantiateCCRequest{
Name: setup.ChainCodeID,
Path: setup.ChaincodeGoPath,
Version: "1.0",
Args: [][]byte{[]byte("init"), []byte("Seller"), []byte("100"), []byte("Buyer"), []byte("200")},
//Args: [][]byte{[]byte("init")},
Policy: ccPolicy,
})
if err != nil || resp.TransactionID == "" {
return errors.WithMessage(err, "failed to instantiate the chaincode")
}
fmt.Println("Chaincode instantiated")
// Channel client is used to query and execute transactions
clientContext := setup.sdk.ChannelContext(setup.ChannelID, fabsdk.WithUser(setup.UserName))
setup.client, err = channel.New(clientContext)
if err != nil {
return errors.WithMessage(err, "failed to create new channel client")
}
fmt.Println("Channel client created")
// Creation of the client which will enables access to our channel events
setup.event, err = event.New(clientContext)
if err != nil {
return errors.WithMessage(err, "failed to create new event client")
}
fmt.Println("Event client created")
fmt.Println("Chaincode Installation & Instantiation Successful")
return nil
}
// CloseSDK to close the sdk connection
func (setup *FabricSetup) CloseSDK() {
setup.sdk.Close()
}
main.go file: calling all the methods in this file
func initializeChannelAndCC(fSetup sdk.FabricSetup) {
err := fSetup.CreateChannel()
if err != nil {
fmt.Printf("Unable to create channel: %v\n", err)
}
err = fSetup.JoinChannel()
if err != nil {
fmt.Printf("Unable to join channel: %v\n", err)
}
err = fSetup.InstallCC()
if err != nil {
fmt.Printf("Unable to install the chaincode: %v\n", err)
}
err = fSetup.InstantiateCC()
if err != nil {
fmt.Printf("Unable to instantiate the chaincode: %v\n", err)
}
}
func main() {
fSetup := sdk.FabricSetup{
OrdererID: "orderer.mytrade.com",
ChannelID: "mychannel",
ChannelConfig: "/c/Projects/Go/src/github.com/hyperledger/myproject/network/channel-artifacts/channel.tx",
ChainCodeID: "myproject",
ChaincodeGoPath: "/c/Projects/Go",
ChaincodePath: "github.com/hyperledger/myproject/chaincode/",
OrgAdmin: "Admin",
OrgName: "Seller",
ConfigFile: "config.yaml",
UserName: "User1",
}
err := fSetup.Initialize()
if err != nil {
fmt.Printf("Unable to initialize the Fabric SDK: %v\n", err)
return
}
defer fSetup.CloseSDK()
initializeChannelAndCC(fSetup)
response, err := fSetup.Query("Seller")
if err != nil {
fmt.Printf("Unable to query the chaincode: %v\n", err)
} else {
fmt.Printf("Response from the query: %s\n", response)
}
}
client-side logging(set to debug mode). These logs are huge hence sharing the link ClientLogs
Please help.
EDIT: added chaincode
type SimpleChaincode struct {
}
// Init method: one time initialisation
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("ex02 Init")
_, args := stub.GetFunctionAndParameters()
var A, B string // Entities
var Aval, Bval int // Asset holdings
var err error
if len(args) != 4 {
return shim.Error("Incorrect number of arguments. Expecting 4")
}
test := strings.Join(args, ", ")
fmt.Println("Value of args is: ", test)
// Initialize the chaincode
A = args[0]
Aval, err = strconv.Atoi(args[1])
if err != nil {
return shim.Error("Expecting integer value for asset holding")
}
B = args[2]
Bval, err = strconv.Atoi(args[3])
if err != nil {
return shim.Error("Expecting integer value for asset holding")
}
fmt.Printf("A = %s, Aval = %d, B = %s, Bval = %d\n", A, Aval, B, Bval)
// Write the state to the ledger
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
// Invoke method: used to sedn the request to the various custom methods
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("ex02 Invoke")
function, args := stub.GetFunctionAndParameters()
if function == "invoke" {
// Make payment of X units from A to B
return t.invoke(stub, args)
} else if function == "delete" {
// Deletes an entity from its state
return t.delete(stub, args)
} else if function == "query" {
// the old "Query" is now implemtned in invoke
return t.query(stub, args)
}
return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")
}
// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var A, B string // Entities
var Aval, Bval int // Asset holdings
var X int // Transaction value
var err error
fmt.Println("Value of args in invoke is: ", strings.Join(args, ", "))
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 3")
}
A = args[0]
B = args[1]
// Get the state from the ledger
// TODO: will be nice to have a GetAllState call to ledger
Avalbytes, err := stub.GetState(A)
if err != nil {
return shim.Error("Failed to get state")
}
if Avalbytes == nil {
return shim.Error("Entity not found")
}
Aval, _ = strconv.Atoi(string(Avalbytes))
Bvalbytes, err := stub.GetState(B)
if err != nil {
return shim.Error("Failed to get state")
}
if Bvalbytes == nil {
return shim.Error("Entity not found")
}
Bval, _ = strconv.Atoi(string(Bvalbytes))
// Perform the execution
X, err = strconv.Atoi(args[2])
if err != nil {
return shim.Error("Invalid transaction amount, expecting a integer value")
}
Aval = Aval - X
Bval = Bval + X
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// Write the state back to the ledger
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
// Deletes an entity from state
func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
A := args[0]
// Delete the key from the state in ledger
err := stub.DelState(A)
if err != nil {
return shim.Error("Failed to delete state")
}
return shim.Success(nil)
}
// query callback representing the query of a chaincode
func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
fmt.Println("Inside query method")
var A string // Entities
var err error
fmt.Println("\value of args in query method is: ", strings.Join(args, ", "))
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting name of the person to query")
}
A = args[0]
// Get the state from the ledger
Avalbytes, err := stub.GetState(A)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
return shim.Error(jsonResp)
}
if Avalbytes == nil {
jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
return shim.Error(jsonResp)
}
jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
fmt.Printf("Query Response:%s\n", jsonResp)
return shim.Success(Avalbytes)
}
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
EDIT
After the run time error, I logged in to peer0.seller.mytrade.com cli using the command
docker exec -it cli bash and ran the peer chaincode query -C mychannel -n myproject -c '{"Args":["query","Seller"]}' command to query the chaincode and I got the result Seller = 100.
Before running the peer chaincode query command, the dev-peer0.seller.mytrade.com container was missing. Only container dev-peer1.seller.mytrade.com exist. But after the peer chaincode query command on peer0.seller.mytrade.com cli resulted in the chaincode container. Since the chaincode invoked on both the peers of Seller then both the containers should be there.
I also added 20s delay because I thought that docker is taking some time to create the container. But it didn't work.
PFA the image of docker ps -a command

Expose kubernetes logs to browser through websocket

I am trying to use sidecar mode in kubernetes to create a logs sidecar to expose specific container logs. And I am using kubernetes client to fetch logs from kubernetes api and send it out by websocket. The code shows below:
func serveWs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
defer conn.Close()
logsClient, err := InitKubeLogsClient(config.InCluster)
if err != nil {
log.Fatalln(err)
}
stream, err := logsClient.GetLogs(config.Namespace, config.PodName, config.ContainerName)
if err != nil {
log.Fatalln(err)
}
defer stream.Close()
reader := bufio.NewReader(stream)
for {
line, err := reader.ReadString('\n')
if err != nil {
log.Fatalln(err)
}
conn.WriteMessage(websocket.TextMessage, []byte(line))
}
}
I am using https://github.com/gorilla/websocket as the websocket lib. And on the browser
Is this the best way to do what I want? Is there some better way to just expose the logs api from k8s to websocket?
Put my final code here, thanks for the tips from #Peter:
func serveWs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
log.Println("create new connection")
defer func() {
conn.Close()
log.Println("connection close")
}()
logsClient, err := InitKubeLogsClient(config.InCluster)
if err != nil {
log.Println(err)
return
}
stream, err := logsClient.GetLogs(config.Namespace, config.PodName, config.ContainerName)
if err != nil {
log.Println(err)
return
}
defer stream.Close()
reader := bufio.NewReaderSize(stream, 16)
lastLine := ""
for {
data, isPrefix, err := reader.ReadLine()
if err != nil {
log.Println(err)
return
}
lines := strings.Split(string(data), "\r")
length := len(lines)
if len(lastLine) > 0 {
lines[0] = lastLine + lines[0]
lastLine = ""
}
if isPrefix {
lastLine = lines[length-1]
lines = lines[:(length - 1)]
}
for _, line := range lines {
if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
log.Println(err)
return
}
}
}
}

Resources