新聞中心
如何理解Fabric SDK開發(fā)中的resmgmt,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
HyperLeger Fabric SDK開發(fā)
一、resmgmt簡介
1、resmgmt簡介
resmgmt支持在Fabric網(wǎng)絡(luò)上創(chuàng)建和更新資源。resmgmt允許管理員創(chuàng)建、更新通道,并允許Peer節(jié)點加入通道。管理員還可以在Peer節(jié)點上執(zhí)行與鏈碼相關(guān)的操作,例如安裝,實例化和升級鏈碼。
官方文檔:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt
2、resmgmt使用流程
resmgmt使用基本流程如下:
A、準(zhǔn)備客戶端上下文
B、創(chuàng)建資源管理客戶端
C、創(chuàng)建新通道
D、將Peer節(jié)點加入通道
E、將鏈碼安裝到Peer節(jié)點的文件系統(tǒng)
F、在通道上實例化鏈碼
G、查詢通道上的Peer節(jié)點,已安裝/實例化的鏈碼等
使用示例:
// 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
二、resmgmt常用接口
1、類型定義
定義鏈碼提案類型
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 }
定義安裝鏈碼響應(yīng)
// 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 }
定義實例化鏈碼響應(yīng)
// 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 }
定義升級鏈碼響應(yīng)
// UpgradeCCResponse contains response parameters for upgrade chaincode type UpgradeCCResponse struct { TransactionID fab.TransactionID }
定義創(chuàng)建通道請求
//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 }
定義創(chuàng)建通道響應(yīng)
// SaveChannelResponse contains response parameters for save channel type SaveChannelResponse struct { TransactionID fab.TransactionID }
2、配置簽名接口
func MarshalConfigSignature(signature *common.ConfigSignature) ([]byte, error)
MarshalConfigSignature為由[]byte級聯(lián)的給定客戶端打包一個ConfigSignature(配置簽名)。func UnmarshalConfigSignature(reader io.Reader) (*common.ConfigSignature, error)
UnmarshalConfigSignature將從reader讀取1個ConfigSignature為[]byte并將其解碼。
3、獲取資源管理客戶端實例
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
4、創(chuàng)建簽名配置
func (rc *Client) CreateConfigSignature(signer msp.SigningIdentity, channelConfigPath string) (*common.ConfigSignature, error)
CreateConfigSignature為指定的客戶端、自定義簽名者、channelConfigPath參數(shù)的通道配置創(chuàng)建一個簽名。
返回由SDK在內(nèi)部簽名的ConfigSignature對象,可以傳遞給WithConfigSignatures()選項。func (rc *Client) CreateConfigSignatureData(signer msp.SigningIdentity, channelConfigPath string) (signatureHeaderData resource.ConfigSignatureData, e error)
CreateConfigSignatureData將準(zhǔn)備一個SignatureHeader和用于簽名通道配置的完整簽名數(shù)據(jù)。
一旦SigningBytes在外部簽名(使用OpenSSL等外部工具簽署signatureHeaderData.SigningBytes),需要執(zhí)行以下操作:
A、創(chuàng)建一個common.ConfigSignature {}實例
B、使用返回的字段'signatureHeaderData.signatureHeader'為其SignatureHeader字段賦值。
C、使用外部工具生成的'signatureHeaderData.signingBytes'簽名為其Signature字段賦值。
D、然后使用WithConfigSignatures()選項傳遞此新實例以進(jìn)行通道更新
5、安裝鏈碼
func (rc *Client) InstallCC(req InstallCCRequest, options ...RequestOption) ([]InstallCCResponse, error)
InstallCC允許管理員將鏈代碼安裝到Peer節(jié)點的文件系統(tǒng)上。如果未在選項中指定Peer節(jié)點,默認(rèn)屬于管理員MSP的所有Peer節(jié)點。
參數(shù):
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關(guān)信息
options包含可選的請求選項
返回:Peer回復(fù)的安裝鏈碼提案的響應(yīng)
使用示例:
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
6、實例化鏈碼
func (rc *Client) InstantiateCC(channelID string, req InstantiateCCRequest, options ...RequestOption) (InstantiateCCResponse, error)
InstantiateCC使用可選的自定義選項(指定Peer節(jié)點,過濾的Peer節(jié)點,超時)實例化鏈碼。如果未在選項中指定Peer節(jié)點,則默認(rèn)為所有通道Peer。
參數(shù):
channelID是必備的通道名稱
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關(guān)信息
options包含可選的請求選項
返回:帶有交易ID的實例化鏈碼響應(yīng)
使用示例:
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
7、加入通道
func (rc *Client) JoinChannel(channelID string, options ...RequestOption) error
JoinChannel允許Peer節(jié)點使用可選的自定義選項(指定Peer節(jié)點,已過濾的Peer節(jié)點)加入現(xiàn)有通道。如果未在選項中指定Peer節(jié)點,則將默認(rèn)為屬于客戶端MSP的所有Peer節(jié)點。
參數(shù):
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
8、查詢通道
func (rc *Client) QueryChannels(options ...RequestOption) (*pb.ChannelQueryResponse, error)
QueryChannels查詢Peer節(jié)點已加入的所有通道的名稱。
參數(shù):
options包含可選的請求選項,注意,必須使用WithTargetURLs或WithTargets請求選項指定一個目標(biāo)Peer節(jié)點。
返回:Peer節(jié)點加入的所有通道
使用示例:
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
9、獲取通道配置
func (rc *Client) QueryConfigFromOrderer(channelID string, options ...RequestOption) (fab.ChannelCfg, error)
QueryConfigFromOrderer從orderer節(jié)點返回通道配置。如果沒有使用選項提供orderer節(jié)點,則將默認(rèn)為通道的orderer節(jié)點(如果已配置)或隨機(jī)從配置中選取orderer節(jié)點。
參數(shù):
channelID是必備的通道ID
options包含可選的請求選項
返回通道的配置
10、查詢已安裝鏈碼
func (rc *Client) QueryInstalledChaincodes(options ...RequestOption) (*pb.ChaincodeQueryResponse, error)
QueryInstalledChaincodes查詢Peer節(jié)點上已安裝的鏈碼。
參數(shù):
options包含可選的請求選項。注意,必須使用WithTargetURLs或WithTargets請求選項指定一個目標(biāo)Peer節(jié)點。
返回:指定Peer節(jié)點上已安裝的鏈碼列表
使用示例:
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
11、查詢已實例化鏈碼
func (rc *Client) QueryInstantiatedChaincodes(channelID string, options ...RequestOption) (*pb.ChaincodeQueryResponse, error)
QueryInstantiatedChaincodes在指定的通道的Peer節(jié)點上的查詢實例化鏈碼。如果沒有在選項中指定Peer節(jié)點,則將在此通道上隨機(jī)查詢一個Peer節(jié)點。
參數(shù):
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
12、創(chuàng)建通道
func (rc *Client) SaveChannel(req SaveChannelRequest, options ...RequestOption) (SaveChannelResponse, error)
SaveChannel創(chuàng)建或更新通道。
參數(shù):
req包含必備的通道名稱和配置的相關(guān)信息
options包含可選的請求選項
如果選項有簽名(WithConfigSignatures()或1個或多個WithConfigSignature()調(diào)用),則SaveChannel將使用選項的簽名而不是為req中找到的SigningIdentities創(chuàng)建一個簽名。
確保req.ChannelConfigPath / req.ChannelConfig具有與簽名匹配的通道配置。
返回帶有交易ID的保存通道響應(yīng)
使用示例:
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
13、升級鏈碼
func (rc *Client) UpgradeCC(channelID string, req UpgradeCCRequest, options ...RequestOption) (UpgradeCCResponse, error)
UpgradeCC使用可選的自定義選項(指定Peer節(jié)點,過濾的Peer節(jié)點,超時)升級鏈碼。如果沒有在選項中指定Peer節(jié)點,則將默認(rèn)為通道的所有Peer節(jié)點。
參數(shù):
channelID是必備的通道名稱
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關(guān)信息
options包含可選的請求選項
返回帶有交易ID的升級鏈碼響應(yīng)
使用示例:
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
14、為客戶端設(shè)置過濾器
type ClientOption func(*Client) error // WithDefaultTargetFilter option to configure default target filter per client func WithDefaultTargetFilter(filter fab.TargetFilter) ClientOption
WithDefaultTargetFilter選項為每個客戶端配置默認(rèn)目標(biāo)過濾器
使用示例:
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
15、RequestOption參數(shù)構(gòu)建
//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調(diào)用提供預(yù)定義的簽名。func WithOrderer(orderer fab.Orderer) RequestOption
WithOrderer允許為請求指定一個orderer節(jié)點。func WithOrdererEndpoint(key string) RequestOption
WithOrdererEndpoint允許為請求指定一個orderer節(jié)點。orderer將根據(jù)key參數(shù)查找。key參數(shù)可以是名稱或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設(shè)置重試選項func WithTargets(targets ...fab.Peer) RequestOption
WithTargets允許覆蓋請求的目標(biāo)Peer節(jié)點。
使用示例:
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允許覆蓋請求的目標(biāo)Peer節(jié)點。目標(biāo)由名稱或URL指定,SDK將創(chuàng)建底層Peer節(jié)點對象。func WithTargetFilter(targetFilter fab.TargetFilter) RequestOption
WithTargetFilter為請求啟用目標(biāo)過濾器。
使用示例:
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的默認(rèn)超時配置。
三、resmgmt示例
var ( sdk *fabsdk.FabricSDK org = "org1" user = "Admin" ) // 區(qū)塊鏈管理 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()) }
看完上述內(nèi)容,你們掌握如何理解Fabric SDK開發(fā)中的resmgmt的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
分享標(biāo)題:如何理解FabricSDK開發(fā)中的resmgmt-創(chuàng)新互聯(lián)
當(dāng)前路徑:http://www.dlmjj.cn/article/ddidjd.html