fabric-sdk-go: github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt Index | Examples | Files

package resmgmt

import "github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"

Package resmgmt enables creation and update of resources on a Fabric network. It allows administrators to create and/or update channnels, and for peers to join channels. Administrators can also perform chaincode related operations on a peer, such as installing, instantiating, and upgrading chaincode.

Basic Flow:
1) Prepare client context
2) Create resource managememt client
3) Create new channel
4) Peer(s) join channel
5) Install chaincode onto peer(s) filesystem
6) Instantiate chaincode on channel
7) Query peer for channels, installed/instantiated chaincodes etc.

Code:

// Create new resource management client
c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

// Read channel configuration tx
channelConfigTxPath := filepath.Join(metadata.GetProjectPath(), metadata.ChannelConfigPath, channelConfigTxFile)
r, err := os.Open(channelConfigTxPath)
if err != nil {
    fmt.Printf("failed to open channel config: %s\n", err)
}
defer r.Close()

// Create new channel 'mychannel'
_, err = c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r})
if err != nil {
    fmt.Printf("failed to save channel: %s\n", err)
}

peer := mockPeer()

// Peer joins channel 'mychannel'
err = c.JoinChannel("mychannel", WithTargets(peer))
if err != nil {
    fmt.Printf("failed to join channel: %s\n", err)
}

// Install example chaincode to peer
installReq := InstallCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Package: &resource.CCPackage{Type: 1, Code: []byte("bytes")}}
_, err = c.InstallCC(installReq, WithTargets(peer))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

// Instantiate example chaincode on channel 'mychannel'
ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
instantiateReq := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}
_, err = c.InstantiateCC("mychannel", instantiateReq, WithTargets(peer))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

fmt.Println("Network setup completed")

Output:

Network setup completed

Index

Examples

Package Files

lscc.go opts.go resmgmt.go

Constants

const (
    InstantiateChaincode chaincodeProposalType = iota
    UpgradeChaincode
)

Define chaincode proposal types

func CalculateConfigUpdate Uses

func CalculateConfigUpdate(channelID string, currentConfig, newConfig *common.Config) (*common.ConfigUpdate, error)

CalculateConfigUpdate calculates channel config update based on the difference between provided current channel config and proposed new channel config.

func MarshalConfigSignature Uses

func MarshalConfigSignature(signature *common.ConfigSignature) ([]byte, error)

MarshalConfigSignature marshals 1 ConfigSignature for the given client concatenated as []byte

func UnmarshalConfigSignature Uses

func UnmarshalConfigSignature(reader io.Reader) (*common.ConfigSignature, error)

UnmarshalConfigSignature reads 1 ConfigSignature as []byte from reader and unmarshals it

type Client Uses

type Client struct {
    // contains filtered or unexported fields
}

Client enables managing resources in Fabric network.

func New Uses

func New(ctxProvider context.ClientProvider, opts ...ClientOption) (*Client, error)

New returns a resource management client instance.

Code:

ctx := mockClientProvider()

c, err := New(ctx)
if err != nil {
    fmt.Println("failed to create client")
}

if c != nil {
    fmt.Println("resource management client created")
}

Output:

resource management client created

func (*Client) CreateConfigSignature Uses

func (rc *Client) CreateConfigSignature(signer msp.SigningIdentity, channelConfigPath string) (*common.ConfigSignature, error)

CreateConfigSignature creates a signature for the given client, custom signers and chConfig from channelConfigPath argument

return ConfigSignature will be signed internally by the SDK. It can be passed to WithConfigSignatures() option

Deprecated: this method is deprecated in order to use CreateConfigSignatureFromReader

func (*Client) CreateConfigSignatureData Uses

func (rc *Client) CreateConfigSignatureData(signer msp.SigningIdentity, channelConfigPath string) (signatureHeaderData resource.ConfigSignatureData, e error)

CreateConfigSignatureData will prepare a SignatureHeader and the full signing []byte (signingBytes) to be used for signing a Channel Config Deprecated: this method is deprecated in order to use CreateConfigSignatureDataFromReader

func (*Client) CreateConfigSignatureDataFromReader Uses

func (rc *Client) CreateConfigSignatureDataFromReader(signer msp.SigningIdentity, channelConfig io.Reader) (signatureHeaderData resource.ConfigSignatureData, e error)

CreateConfigSignatureDataFromReader will prepare a SignatureHeader and the full signing []byte (signingBytes) to be used for signing a Channel Config

	Once SigningBytes have been signed externally (signing signatureHeaderData.SigningBytes using an external tool like OpenSSL), do the following:
 1. create a common.ConfigSignature{} instance
 2. assign its SignatureHeader field with the returned field 'signatureHeaderData.signatureHeader'
 3. assign its Signature field with the generated signature of 'signatureHeaderData.signingBytes' from the external tool
 Then use WithConfigSignatures() option to pass this new instance for channel updates

func (*Client) CreateConfigSignatureFromReader Uses

func (rc *Client) CreateConfigSignatureFromReader(signer msp.SigningIdentity, channelConfig io.Reader) (*common.ConfigSignature, error)

CreateConfigSignatureFromReader creates a signature for the given client, custom signers and chConfig from io.Reader argument

return ConfigSignature will be signed internally by the SDK. It can be passed to WithConfigSignatures() option

func (*Client) InstallCC Uses

func (rc *Client) InstallCC(req InstallCCRequest, options ...RequestOption) ([]InstallCCResponse, error)

InstallCC allows administrators to install chaincode onto the filesystem of a peer. If peer(s) are not specified in options it will default to all peers that belong to admin's MSP.

Parameters:
req holds info about mandatory chaincode name, path, version and policy
options holds optional request options

Returns:
install chaincode proposal responses from peer(s)

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

req := InstallCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Package: &resource.CCPackage{Type: 1, Code: []byte("bytes")}}
responses, err := c.InstallCC(req, WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

if len(responses) > 0 {
    fmt.Println("Chaincode installed")
}

Output:

Chaincode installed

func (*Client) InstantiateCC Uses

func (rc *Client) InstantiateCC(channelID string, req InstantiateCCRequest, options ...RequestOption) (InstantiateCCResponse, error)

InstantiateCC instantiates chaincode with optional custom options (specific peers, filtered peers, timeout). If peer(s) are not specified in options it will default to all channel peers.

Parameters:
channel is manadatory channel name
req holds info about mandatory chaincode name, path, version and policy
options holds optional request options

Returns:
instantiate chaincode response with transaction ID

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
req := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}

resp, err := c.InstantiateCC("mychannel", req)
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to instantiate chaincode")
}

fmt.Println("Chaincode instantiated")

Output:

Chaincode instantiated

func (*Client) JoinChannel Uses

func (rc *Client) JoinChannel(channelID string, options ...RequestOption) error

JoinChannel allows for peers to join existing channel with optional custom options (specific peers, filtered peers). If peer(s) are not specified in options it will default to all peers that belong to client's MSP.

Parameters:
channel is manadatory channel name
options holds optional request options

Returns:
an error if join fails

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

err = c.JoinChannel("mychannel", WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to join channel: %s\n", err)
}

fmt.Println("Joined channel")

Output:

Joined channel

func (*Client) QueryChannels Uses

func (rc *Client) QueryChannels(options ...RequestOption) (*pb.ChannelQueryResponse, error)

QueryChannels queries the names of all the channels that a peer has joined.

Parameters:
options hold optional request options
Note: One target(peer) has to be specified using either WithTargetURLs or WithTargets request option

Returns:
all channels that peer has joined

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryChannels(WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query channels: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved channels")
}

Output:

Retrieved channels

func (*Client) QueryCollectionsConfig Uses

func (rc *Client) QueryCollectionsConfig(channelID string, chaincodeName string, options ...RequestOption) (*common.CollectionConfigPackage, error)

QueryCollectionsConfig queries the collections config on a peer for specific channel. If peer is not specified in options it will query random peer on this channel. Parameters: channel is mandatory channel name chaincode is mandatory chaincode name options hold optional request options

Returns: list of collections config

func (*Client) QueryConfigBlockFromOrderer Uses

func (rc *Client) QueryConfigBlockFromOrderer(channelID string, options ...RequestOption) (*common.Block, error)

QueryConfigBlockFromOrderer config returns channel configuration block from orderer. If orderer is not provided using options it will be defaulted to channel orderer (if configured) or random orderer from configuration.

Parameters:
channelID is mandatory channel ID
options holds optional request options

Returns:
channel configuration block

func (*Client) QueryConfigFromOrderer Uses

func (rc *Client) QueryConfigFromOrderer(channelID string, options ...RequestOption) (fab.ChannelCfg, error)

QueryConfigFromOrderer config returns channel configuration from orderer. If orderer is not provided using options it will be defaulted to channel orderer (if configured) or random orderer from configuration.

Parameters:
channelID is mandatory channel ID
options holds optional request options

Returns:
channel configuration

func (*Client) QueryInstalledChaincodes Uses

func (rc *Client) QueryInstalledChaincodes(options ...RequestOption) (*pb.ChaincodeQueryResponse, error)

QueryInstalledChaincodes queries the installed chaincodes on a peer.

Parameters:
options hold optional request options
Note: One target(peer) has to be specified using either WithTargetURLs or WithTargets request option

Returns:
list of installed chaincodes on specified peer

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryInstalledChaincodes(WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query installed chaincodes: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved installed chaincodes")
}

Output:

Retrieved installed chaincodes

func (*Client) QueryInstantiatedChaincodes Uses

func (rc *Client) QueryInstantiatedChaincodes(channelID string, options ...RequestOption) (*pb.ChaincodeQueryResponse, error)

QueryInstantiatedChaincodes queries the instantiated chaincodes on a peer for specific channel. If peer is not specified in options it will query random peer on this channel.

Parameters:
channel is manadatory channel name
options hold optional request options

Returns:
list of instantiated chaincodes

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryInstantiatedChaincodes("mychannel", WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query instantiated chaincodes: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved instantiated chaincodes")
}

Output:

Retrieved instantiated chaincodes

func (*Client) SaveChannel Uses

func (rc *Client) SaveChannel(req SaveChannelRequest, options ...RequestOption) (SaveChannelResponse, error)

SaveChannel creates or updates channel.

 Parameters:
 req holds info about mandatory channel name and configuration
 options holds optional request options
 if options have signatures (WithConfigSignatures() or 1 or more WithConfigSignature() calls), then SaveChannel will
    use these signatures instead of creating ones for the SigningIdentities found in req.
	   Make sure that req.ChannelConfigPath/req.ChannelConfig have the channel config matching these signatures.

 Returns:
 save channel response with transaction ID

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Printf("failed to create client: %s\n", err)
}

channelConfigTxPath := filepath.Join(metadata.GetProjectPath(), metadata.ChannelConfigPath, channelConfigTxFile)
r, err := os.Open(channelConfigTxPath)
if err != nil {
    fmt.Printf("failed to open channel config: %s\n", err)
}
defer r.Close()

resp, err := c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r})
if err != nil {
    fmt.Printf("failed to save channel: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to save channel")
}

fmt.Println("Saved channel")

Output:

Saved channel

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Printf("failed to create client: %s\n", err)
}

channelConfigTxPath := filepath.Join(metadata.GetProjectPath(), metadata.ChannelConfigPath, channelConfigTxFile)
r, err := os.Open(channelConfigTxPath)
if err != nil {
    fmt.Printf("failed to open channel config: %s\n", err)
}
defer r.Close()

resp, err := c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r}, WithOrdererEndpoint("example.com"))
if err != nil {
    fmt.Printf("failed to save channel: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to save channel")
}

fmt.Println("Saved channel")

Output:

Saved channel

func (*Client) UpgradeCC Uses

func (rc *Client) UpgradeCC(channelID string, req UpgradeCCRequest, options ...RequestOption) (UpgradeCCResponse, error)

UpgradeCC upgrades chaincode with optional custom options (specific peers, filtered peers, timeout). If peer(s) are not specified in options it will default to all channel peers.

Parameters:
channel is manadatory channel name
req holds info about mandatory chaincode name, path, version and policy
options holds optional request options

Returns:
upgrade chaincode response with transaction ID

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
req := UpgradeCCRequest{Name: "ExampleCC", Version: "v1", Path: "path", Policy: ccPolicy}

resp, err := c.UpgradeCC("mychannel", req, WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to upgrade chaincode: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to upgrade chaincode")
}

fmt.Println("Chaincode upgraded")

Output:

Chaincode upgraded

type ClientOption Uses

type ClientOption func(*Client) error

ClientOption describes a functional parameter for the New constructor

func WithDefaultTargetFilter Uses

func WithDefaultTargetFilter(filter fab.TargetFilter) ClientOption

WithDefaultTargetFilter option to configure default target filter per client

Code:

ctx := mockClientProvider()

c, err := New(ctx, WithDefaultTargetFilter(&urlTargetFilter{url: "example.com"}))
if err != nil {
    fmt.Println("failed to create client")
}

if c != nil {
    fmt.Println("resource management client created with url target filter")
}

Output:

resource management client created with url target filter

type InstallCCRequest Uses

type InstallCCRequest struct {
    Name    string
    Path    string
    Version string
    Package *resource.CCPackage
}

InstallCCRequest contains install chaincode request parameters

type InstallCCResponse Uses

type InstallCCResponse struct {
    Target string
    Status int32
    Info   string
}

InstallCCResponse contains install chaincode response status

type InstantiateCCRequest Uses

type InstantiateCCRequest struct {
    Name       string
    Path       string
    Version    string
    Args       [][]byte
    Policy     *common.SignaturePolicyEnvelope
    CollConfig []*common.CollectionConfig
}

InstantiateCCRequest contains instantiate chaincode request parameters

type InstantiateCCResponse Uses

type InstantiateCCResponse struct {
    TransactionID fab.TransactionID
}

InstantiateCCResponse contains response parameters for instantiate chaincode

type RequestOption Uses

type RequestOption func(ctx context.Client, opts *requestOptions) error

RequestOption func for each Opts argument

func WithConfigSignatures Uses

func WithConfigSignatures(signatures ...*common.ConfigSignature) RequestOption

WithConfigSignatures allows to provide pre defined signatures for resmgmt client's SaveChannel call

func WithOrderer Uses

func WithOrderer(orderer fab.Orderer) RequestOption

WithOrderer allows an orderer to be specified for the request.

func WithOrdererEndpoint Uses

func WithOrdererEndpoint(key string) RequestOption

WithOrdererEndpoint allows an orderer to be specified for the request. The orderer will be looked-up based on the key argument. key argument can be a name or url

func WithParentContext Uses

func WithParentContext(parentContext reqContext.Context) RequestOption

WithParentContext encapsulates grpc parent context.

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

clientContext, err := mockClientProvider()()
if err != nil {
    fmt.Println("failed to return client context")
    return
}

// get parent context and cancel
parentContext, cancel := sdkCtx.NewRequest(clientContext, sdkCtx.WithTimeout(20*time.Second))
defer cancel()

channels, err := c.QueryChannels(WithParentContext(parentContext), WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query for blockchain info: %s\n", err)
}

if channels != nil {
    fmt.Println("Retrieved channels that peer belongs to")
}

Output:

Retrieved channels that peer belongs to

func WithRetry Uses

func WithRetry(retryOpt retry.Opts) RequestOption

WithRetry sets retry options.

func WithTargetEndpoints Uses

func WithTargetEndpoints(keys ...string) RequestOption

WithTargetEndpoints allows overriding of the target peers for the request. Targets are specified by name or URL, and the SDK will create the underlying peer objects.

func WithTargetFilter Uses

func WithTargetFilter(targetFilter fab.TargetFilter) RequestOption

WithTargetFilter enables a target filter for the request.

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
req := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}

resp, err := c.InstantiateCC("mychannel", req, WithTargetFilter(&urlTargetFilter{url: "http://peer1.com"}))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to instantiate chaincode")
}

fmt.Println("Chaincode instantiated")

Output:

Chaincode instantiated

func WithTargets Uses

func WithTargets(targets ...fab.Peer) RequestOption

WithTargets allows overriding of the target peers for the request.

Code:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryChannels(WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query channels: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved channels")
}

Output:

Retrieved channels

func WithTimeout Uses

func WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption

WithTimeout encapsulates key value pairs of timeout type, timeout duration to Options if not provided, default timeout configuration from config will be used

type SaveChannelRequest Uses

type SaveChannelRequest struct {
    ChannelID         string
    ChannelConfig     io.Reader // ChannelConfig data source
    ChannelConfigPath string    // Convenience option to use the named file as ChannelConfig reader
    // Users that sign channel configuration
    // deprecated - one entity shouldn't have access to another entities' keys to sign on their behalf
    SigningIdentities []msp.SigningIdentity
}

SaveChannelRequest holds parameters for save channel request

type SaveChannelResponse Uses

type SaveChannelResponse struct {
    TransactionID fab.TransactionID
}

SaveChannelResponse contains response parameters for save channel

type UpgradeCCRequest Uses

type UpgradeCCRequest struct {
    Name       string
    Path       string
    Version    string
    Args       [][]byte
    Policy     *common.SignaturePolicyEnvelope
    CollConfig []*common.CollectionConfig
}

UpgradeCCRequest contains upgrade chaincode request parameters

type UpgradeCCResponse Uses

type UpgradeCCResponse struct {
    TransactionID fab.TransactionID
}

UpgradeCCResponse contains response parameters for upgrade chaincode

Package resmgmt imports 27 packages (graph) and is imported by 8 packages. Updated 2019-09-18. Refresh now. Tools for package owners.