您好,登錄后才能下訂單哦!
如何理解Fabric SDK開發中的resmgmt,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
resmgmt支持在Fabric網絡上創建和更新資源。resmgmt允許管理員創建、更新通道,并允許Peer節點加入通道。管理員還可以在Peer節點上執行與鏈碼相關的操作,例如安裝,實例化和升級鏈碼。
官方文檔:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt
resmgmt使用基本流程如下:
A、準備客戶端上下文
B、創建資源管理客戶端
C、創建新通道
D、將Peer節點加入通道
E、將鏈碼安裝到Peer節點的文件系統
F、在通道上實例化鏈碼
G、查詢通道上的Peer節點,已安裝/實例化的鏈碼等
使用示例:
// Create new resource management client c, err := New(mockClientProvider()) if err != nil { fmt.Println("failed to create client") } // Read channel configuration r, err := os.Open(channelConfig) 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
定義鏈碼提案類型
type chaincodeProposalType int // Define chaincode proposal types const ( InstantiateChaincode chaincodeProposalType = iota UpgradeChaincode )
定義安裝鏈碼請求
// InstallCCRequest contains install chaincode request parameters type InstallCCRequest struct { Name string Path string Version string Package *resource.CCPackage }
定義安裝鏈碼響應
// InstallCCResponse contains install chaincode response status type InstallCCResponse struct { Target string Status int32 Info string }
定義實例化鏈碼請求
// InstantiateCCRequest contains instantiate chaincode request parameters type InstantiateCCRequest struct { Name string Path string Version string Args [][]byte Policy *common.SignaturePolicyEnvelope CollConfig []*common.CollectionConfig }
定義實例化鏈碼響應
// InstantiateCCResponse contains response parameters for instantiate chaincode type InstantiateCCResponse struct { TransactionID fab.TransactionID }
定義升級鏈碼請求
// UpgradeCCRequest contains upgrade chaincode request parameters type UpgradeCCRequest struct { Name string Path string Version string Args [][]byte Policy *common.SignaturePolicyEnvelope CollConfig []*common.CollectionConfig }
定義升級鏈碼響應
// UpgradeCCResponse contains response parameters for upgrade chaincode type UpgradeCCResponse struct { TransactionID fab.TransactionID }
定義創建通道請求
//SaveChannelRequest holds parameters for save channel request type SaveChannelRequest struct { ChannelID string ChannelConfig io.Reader // ChannelConfig data source ChannelConfigPath string // Convenience option to use the named file as ChannelConfig reader SigningIdentities []msp.SigningIdentity // Users that sign channel configuration }
定義創建通道響應
// SaveChannelResponse contains response parameters for save channel type SaveChannelResponse struct { TransactionID fab.TransactionID }
func MarshalConfigSignature(signature *common.ConfigSignature) ([]byte, error)
MarshalConfigSignature為由[]byte級聯的給定客戶端打包一個ConfigSignature(配置簽名)。func UnmarshalConfigSignature(reader io.Reader) (*common.ConfigSignature, error)
UnmarshalConfigSignature將從reader讀取1個ConfigSignature為[]byte并將其解碼。
type Client struct { ctx context.Client filter fab.TargetFilter localCtxProvider context.LocalProvider } func New(ctxProvider context.ClientProvider, opts ...ClientOption) (*Client, error)
New返回資源管理客戶端實例。
使用示例:
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 (rc *Client) CreateConfigSignature(signer msp.SigningIdentity, channelConfigPath string) (*common.ConfigSignature, error)
CreateConfigSignature為指定的客戶端、自定義簽名者、channelConfigPath參數的通道配置創建一個簽名。
返回由SDK在內部簽名的ConfigSignature對象,可以傳遞給WithConfigSignatures()選項。func (rc *Client) CreateConfigSignatureData(signer msp.SigningIdentity, channelConfigPath string) (signatureHeaderData resource.ConfigSignatureData, e error)
CreateConfigSignatureData將準備一個SignatureHeader和用于簽名通道配置的完整簽名數據。
一旦SigningBytes在外部簽名(使用OpenSSL等外部工具簽署signatureHeaderData.SigningBytes),需要執行以下操作:
A、創建一個common.ConfigSignature {}實例
B、使用返回的字段'signatureHeaderData.signatureHeader'為其SignatureHeader字段賦值。
C、使用外部工具生成的'signatureHeaderData.signingBytes'簽名為其Signature字段賦值。
D、然后使用WithConfigSignatures()選項傳遞此新實例以進行通道更新
func (rc *Client) InstallCC(req InstallCCRequest, options ...RequestOption) ([]InstallCCResponse, error)
InstallCC允許管理員將鏈代碼安裝到Peer節點的文件系統上。如果未在選項中指定Peer節點,默認屬于管理員MSP的所有Peer節點。
參數:
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關信息
options包含可選的請求選項
返回:Peer回復的安裝鏈碼提案的響應
使用示例:
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 (rc *Client) InstantiateCC(channelID string, req InstantiateCCRequest, options ...RequestOption) (InstantiateCCResponse, error)
InstantiateCC使用可選的自定義選項(指定Peer節點,過濾的Peer節點,超時)實例化鏈碼。如果未在選項中指定Peer節點,則默認為所有通道Peer。
參數:
channelID是必備的通道名稱
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關信息
options包含可選的請求選項
返回:帶有交易ID的實例化鏈碼響應
使用示例:
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 (rc *Client) JoinChannel(channelID string, options ...RequestOption) error
JoinChannel允許Peer節點使用可選的自定義選項(指定Peer節點,已過濾的Peer節點)加入現有通道。如果未在選項中指定Peer節點,則將默認為屬于客戶端MSP的所有Peer節點。
參數:
channelID是必備的通道名稱
options包含可選的請求選項
返回:如果加入通道失敗,返回錯誤
使用示例:
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 (rc *Client) QueryChannels(options ...RequestOption) (*pb.ChannelQueryResponse, error)
QueryChannels查詢Peer節點已加入的所有通道的名稱。
參數:
options包含可選的請求選項,注意,必須使用WithTargetURLs或WithTargets請求選項指定一個目標Peer節點。
返回:Peer節點加入的所有通道
使用示例:
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 (rc *Client) QueryConfigFromOrderer(channelID string, options ...RequestOption) (fab.ChannelCfg, error)
QueryConfigFromOrderer從orderer節點返回通道配置。如果沒有使用選項提供orderer節點,則將默認為通道的orderer節點(如果已配置)或隨機從配置中選取orderer節點。
參數:
channelID是必備的通道ID
options包含可選的請求選項
返回通道的配置
func (rc *Client) QueryInstalledChaincodes(options ...RequestOption) (*pb.ChaincodeQueryResponse, error)
QueryInstalledChaincodes查詢Peer節點上已安裝的鏈碼。
參數:
options包含可選的請求選項。注意,必須使用WithTargetURLs或WithTargets請求選項指定一個目標Peer節點。
返回:指定Peer節點上已安裝的鏈碼列表
使用示例:
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 (rc *Client) QueryInstantiatedChaincodes(channelID string, options ...RequestOption) (*pb.ChaincodeQueryResponse, error)
QueryInstantiatedChaincodes在指定的通道的Peer節點上的查詢實例化鏈碼。如果沒有在選項中指定Peer節點,則將在此通道上隨機查詢一個Peer節點。
參數:
channelID是必填通道名稱
options包含可選的請求選項
返回實例化鏈碼列表
使用示例:
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 (rc *Client) SaveChannel(req SaveChannelRequest, options ...RequestOption) (SaveChannelResponse, error)
SaveChannel創建或更新通道。
參數:
req包含必備的通道名稱和配置的相關信息
options包含可選的請求選項
如果選項有簽名(WithConfigSignatures()或1個或多個WithConfigSignature()調用),則SaveChannel將使用選項的簽名而不是為req中找到的SigningIdentities創建一個簽名。
確保req.ChannelConfigPath / req.ChannelConfig具有與簽名匹配的通道配置。
返回帶有交易ID的保存通道響應
使用示例:
c, err := New(mockClientProvider()) if err != nil { fmt.Printf("failed to create client: %s\n", err) } r, err := os.Open(channelConfig) 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
使用WithOrdererEndpoint
c, err := New(mockClientProvider()) if err != nil { fmt.Printf("failed to create client: %s\n", err) } r, err := os.Open(channelConfig) 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 (rc *Client) UpgradeCC(channelID string, req UpgradeCCRequest, options ...RequestOption) (UpgradeCCResponse, error)
UpgradeCC使用可選的自定義選項(指定Peer節點,過濾的Peer節點,超時)升級鏈碼。如果沒有在選項中指定Peer節點,則將默認為通道的所有Peer節點。
參數:
channelID是必備的通道名稱
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關信息
options包含可選的請求選項
返回帶有交易ID的升級鏈碼響應
使用示例:
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 func(*Client) error // WithDefaultTargetFilter option to configure default target filter per client func WithDefaultTargetFilter(filter fab.TargetFilter) ClientOption
WithDefaultTargetFilter選項為每個客戶端配置默認目標過濾器
使用示例:
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
//RequestOption func for each Opts argument type RequestOption func(ctx context.Client, opts *requestOptions) error type requestOptions struct { Targets []fab.Peer // target peers TargetFilter fab.TargetFilter // target filter Orderer fab.Orderer // use specific orderer Timeouts map[fab.TimeoutType]time.Duration //timeout options for resmgmt operations ParentContext reqContext.Context //parent grpc context for resmgmt operations Retry retry.Opts // signatures for channel configurations, if set, this option will take precedence over signatures of SaveChannelRequest.SigningIdentities Signatures []*common.ConfigSignature } func WithConfigSignatures(signatures ...*common.ConfigSignature) RequestOption
WithConfigSignatures允許為resmgmt客戶端的SaveChannel調用提供預定義的簽名。func WithOrderer(orderer fab.Orderer) RequestOption
WithOrderer允許為請求指定一個orderer節點。func WithOrdererEndpoint(key string) RequestOption
WithOrdererEndpoint允許為請求指定一個orderer節點。orderer將根據key參數查找。key參數可以是名稱或url。func WithParentContext(parentContext reqContext.Context) RequestOption
WithParentContext封裝了grpc父對象上下文
使用示例:
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(retryOpt retry.Opts) RequestOption
WithRetry設置重試選項func WithTargets(targets ...fab.Peer) RequestOption
WithTargets允許覆蓋請求的目標Peer節點。
使用示例:
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 WithTargetEndpoints(keys ...string) RequestOption
WithTargetEndpoints允許覆蓋請求的目標Peer節點。目標由名稱或URL指定,SDK將創建底層Peer節點對象。func WithTargetFilter(targetFilter fab.TargetFilter) RequestOption
WithTargetFilter為請求啟用目標過濾器。
使用示例:
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 WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption
WithTimeout封裝了超時類型、超時時間的鍵值對到選項,如果未提供,則使用config的默認超時配置。
var ( sdk *fabsdk.FabricSDK org = "org1" user = "Admin" ) // 區塊鏈管理 func manageBlockchain() { // 表明身份 ctx := sdk.Context(fabsdk.WithOrg(org), fabsdk.WithUser(user)) cli, err := resmgmt.New(ctx) if err != nil { panic(err) } // 具體操作 cli.SaveChannel(resmgmt.SaveChannelRequest{}, resmgmt.WithOrdererEndpoint("orderer.example.com"), resmgmt.WithTargetEndpoints()) }
看完上述內容,你們掌握如何理解Fabric SDK開發中的resmgmt的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。