pkg/client/resmgmt resmgmt包

一. pkg/client/resmgmt 包resmgmt支持在Fabric网络上创建和更新资源。 它允许管理员创建和/或更新通道,并允许管理员加入通道。 管理员还可以在对等方上执行与链代码相关的操作,例如安装,实例化和升级链代码.

  1. 基本流程:

    1)准备客户端上下文
    2)创建资源管理客户端
    3)创建新频道
    4)Peer(s)加入频道
    5)将链代码安装到peer(s)文件系统
    6)在通道上实例化链码
    7)查询peer通道,已安装/实例化的链代码等。

     1 // Create new resource management client
     2 c, err := New(mockClientProvider())
     3 if err != nil {
     4     fmt.Println("failed to create client")
     5 }
     6 
     7 // Read channel configuration
     8 r, err := os.Open(channelConfig)
     9 if err != nil {
    10     fmt.Printf("failed to open channel config: %s\n", err)
    11 }
    12 defer r.Close()
    13 
    14 // Create new channel 'mychannel'
    15 _, err = c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r})
    16 if err != nil {
    17     fmt.Printf("failed to save channel: %s\n", err)
    18 }
    19 
    20 peer := mockPeer()
    21 
    22 // Peer joins channel 'mychannel'
    23 err = c.JoinChannel("mychannel", WithTargets(peer))
    24 if err != nil {
    25     fmt.Printf("failed to join channel: %s\n", err)
    26 }
    27 
    28 // Install example chaincode to peer
    29 installReq := InstallCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Package: &resource.CCPackage{Type: 1, Code: []byte("bytes")}}
    30 _, err = c.InstallCC(installReq, WithTargets(peer))
    31 if err != nil {
    32     fmt.Printf("failed to install chaincode: %s\n", err)
    33 }
    34 
    35 // Instantiate example chaincode on channel 'mychannel'
    36 ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
    37 instantiateReq := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}
    38 _, err = c.InstantiateCC("mychannel", instantiateReq, WithTargets(peer))
    39 if err != nil {
    40     fmt.Printf("failed to install chaincode: %s\n", err)
    41 }
    42 
    43 fmt.Println("Network setup completed")
    View Code

    输出:Network setup completed

  2. 常量
    1. const (
          InstantiateChaincode chaincodeProposalType = iota
          UpgradeChaincode
      ): 定义链代码提议类型
  3. func MarshalConfigSignature(signature *common.ConfigSignature) ([]byte, error): MarshalConfigSignature给定客户端连接为[]byte的ConfigSignature(配置签名)
  4. func UnmarshalConfigSignature(reader io.Reader) (*common.ConfigSignature, error): UnmarshalConfigSignature将1个ConfigSignature从reader读取为[]byte并将其解码.
  5. 类型Client
    1. type Client struct {// contains filtered or unexported fields}: 客户端可以管理Fabric网络中的资源。
    2. func New(ctxProvider context.ClientProvider, opts ...ClientOption) (*Client, error): New返回资源管理客户端实例。
      1. 例:
         1 ctx := mockClientProvider()
         2 
         3 c, err := New(ctx)
         4 if err != nil {
         5     fmt.Println("failed to create client")
         6 }
         7 
         8 if c != nil {
         9     fmt.Println("resource management client created")
        10 }
        View Code

        输出:resource management client created

    3. func (rc *Client) CreateConfigSignature(signer msp.SigningIdentity, channelConfigPath string) (*common.ConfigSignature, error): CreateConfigSignature根据channelConfigPath参数为给定客户端,自定义签名者和chConfig创建签名
      1. 参数:返回ConfigSignature将由SDK在内部签名。 它可以传递给WithConfigSignatures()选项
    func (rc *Client) CreateConfigSignatureData(signer msp.SigningIdentity, channelConfigPath string) (signatureHeaderData resource.ConfigSignatureData, e error): CreateConfigSignatureData将准备一个SignatureHeader和完整的sign []byte (signingBytes),这些符号将用于签名通道配置
      1. 一旦SigningBytes在外部签名(使用OpenSSL等外部工具签署signatureHeaderData.SigningBytes),请执行以下操作:
          1.创建一个common.ConfigSignature {}实例
          2.为其SignatureHeader字段分配返回的字段'signatureHeaderData.signatureHeader'
          3.从外部工具为其Signature字段分配生成的'signatureHeaderData.signingBytes'签名
          然后使用WithConfigSignatures()选项传递此新实例以进行通道更新

    1. func (rc *Client) InstallCC(req InstallCCRequest, options ...RequestOption) ([]InstallCCResponse, error): InstallCC允许管理员将链代码安装到peer的文件系统上。 如果未在选项中指定peer,则它将默认为属于管理员MSP的所有peer。
      1. 参数:

        req包含有关强制链代码名称,路径,版本和策略的信息
        options包含可选的请求选项

        返回:
        安装来自peer的链码提议回复

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 req := InstallCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Package: &resource.CCPackage{Type: 1, Code: []byte("bytes")}}
         7 responses, err := c.InstallCC(req, WithTargets(mockPeer()))
         8 if err != nil {
         9     fmt.Printf("failed to install chaincode: %s\n", err)
        10 }
        11 
        12 if len(responses) > 0 {
        13     fmt.Println("Chaincode installed")
        14 }
        View Code

        输出: Chaincode installed

    2. func (rc *Client) InstantiateCC(channelID string, req InstantiateCCRequest, options ...RequestOption) (InstantiateCCResponse, error): InstantiateCC使用可选的自定义选项(特定peer,过滤的peer,超时)实例化链码。 如果未在选项中指定peer,则它将默认为所有通道peer。
      1. 参数:

        渠道是管理频道的名称
        req包含有关强制链代码名称,路径,版本和策略的信息
        options包含可选的请求选项

        返回:
        使用事务ID实例化链代码响应

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
         7 req := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}
         8 
         9 resp, err := c.InstantiateCC("mychannel", req)
        10 if err != nil {
        11     fmt.Printf("failed to install chaincode: %s\n", err)
        12 }
        13 
        14 if resp.TransactionID == "" {
        15     fmt.Println("Failed to instantiate chaincode")
        16 }
        17 
        18 fmt.Println("Chaincode instantiated")
        View Code

        输出:Chaincode instantiated

    3. func (rc *Client) JoinChannel(channelID string, options ...RequestOption) error: JoinChannel允许peer使用可选的自定义选项(特定peer,已过滤的peer)加入现有通道。 如果未在选项中指定peer,则它将默认为属于客户端MSP的所有peer。
      1. 参数:

        channel是必填通道名称
        options包含可选的请求选项
        返回:
        加入失败时出错

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 err = c.JoinChannel("mychannel", WithTargets(mockPeer()))
         7 if err != nil {
         8     fmt.Printf("failed to join channel: %s\n", err)
         9 }
        10 
        11 fmt.Println("Joined channel")
        View Code

        输出:Joined channel

    4. func (rc *Client) QueryChannels(options ...RequestOption) (*pb.ChannelQueryResponse, error): QueryChannels查询peer已加入的所有通道的名称。
      1. 参数:

        options包含可选的请求选项
        注意:必须使用WithTargetURLs或WithTargets请求选项指定一个目标(peer)

        返回:
        peer加入的所有渠道

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 response, err := c.QueryChannels(WithTargets(mockPeer()))
         7 if err != nil {
         8     fmt.Printf("failed to query channels: %s\n", err)
         9 }
        10 
        11 if response != nil {
        12     fmt.Println("Retrieved channels")
        13 }
        View Code

        输出:Retrieved channels

    5. func (rc *Client) QueryConfigFromOrderer(channelID string, options ...RequestOption) (fab.ChannelCfg, error): QueryConfigFromOrderer配置从orderer返回通道配置。 如果未使用选项提供orderer,则将默认为渠道orderer(如果已配置)或随机orderer。
      1. 参数:

        channelID是必填通道ID
        options包含可选的请求选项

        返回:
        渠道配置

    6. func (rc *Client) QueryInstalledChaincodes(options ...RequestOption) (*pb.ChaincodeQueryResponse, error): QueryInstalledChaincodes查询peer上已安装的链代码。
      1. 参数:

        options包含可选的请求选项
        注意:必须使用WithTargetURLs或WithTargets请求选项指定一个目标(peer)

        返回:
        指定peer上已安装的链代码列表

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 response, err := c.QueryInstalledChaincodes(WithTargets(mockPeer()))
         7 if err != nil {
         8     fmt.Printf("failed to query installed chaincodes: %s\n", err)
         9 }
        10 
        11 if response != nil {
        12     fmt.Println("Retrieved installed chaincodes")
        13 }
        View Code

        输出:Retrieved installed chaincodes

    7. func (rc *Client) QueryInstantiatedChaincodes(channelID string, options ...RequestOption) (*pb.ChaincodeQueryResponse, error): QueryInstantiatedChaincodes查询peer上的实例化链代码以查找特定通道。 如果未在选项中指定peer,则它将在此通道上查询随机peer。
      1. 参数:

        channel是必填通道名称
        options包含可选的请求选项
        返回:
        实例化链代码列表

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 response, err := c.QueryInstantiatedChaincodes("mychannel", WithTargets(mockPeer()))
         7 if err != nil {
         8     fmt.Printf("failed to query instantiated chaincodes: %s\n", err)
         9 }
        10 
        11 if response != nil {
        12     fmt.Println("Retrieved instantiated chaincodes")
        13 }
        View Code

        输出:Retrieved instantiated chaincodes

    8. func (rc *Client) SaveChannel(req SaveChannelRequest, options ...RequestOption) (SaveChannelResponse, error): SaveChannel创建或更新频道。
      1. 参数:

        req包含有关强制通道名称和配置的信息
          options包含可选的请求选项
          如果选项有签名(WithConfigSignatures()或1个或多个WithConfigSignature()调用),则SaveChannel将
             使用这些签名而不是为req中找到的SigningIdentities创建一个签名。
        确保req.ChannelConfigPath / req.ChannelConfig具有与这些签名匹配的通道配置。

         返回:
          使用事务ID保存通道响应

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Printf("failed to create client: %s\n", err)
         4 }
         5 
         6 r, err := os.Open(channelConfig)
         7 if err != nil {
         8     fmt.Printf("failed to open channel config: %s\n", err)
         9 }
        10 defer r.Close()
        11 
        12 resp, err := c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r})
        13 if err != nil {
        14     fmt.Printf("failed to save channel: %s\n", err)
        15 }
        16 
        17 if resp.TransactionID == "" {
        18     fmt.Println("Failed to save channel")
        19 }
        20 
        21 fmt.Println("Saved channel")
        View Code

        输出:Saved channel

      3. 例:WithOrdererEndpoint
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Printf("failed to create client: %s\n", err)
         4 }
         5 
         6 r, err := os.Open(channelConfig)
         7 if err != nil {
         8     fmt.Printf("failed to open channel config: %s\n", err)
         9 }
        10 defer r.Close()
        11 
        12 resp, err := c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r}, WithOrdererEndpoint("example.com"))
        13 if err != nil {
        14     fmt.Printf("failed to save channel: %s\n", err)
        15 }
        16 
        17 if resp.TransactionID == "" {
        18     fmt.Println("Failed to save channel")
        19 }
        20 
        21 fmt.Println("Saved channel")
        View Code

        输出:Saved channel

    9. func (rc *Client) UpgradeCC(channelID string, req UpgradeCCRequest, options ...RequestOption) (UpgradeCCResponse, error): UpgradeCC使用可选的自定义选项(特定peer,过滤的peer,超时)升级链码。 如果未在选项中指定peer,则它将默认为所有通道peer。
      1. 参数:

        渠道是管理频道的名称
        req包含有关强制链代码名称,路径,版本和策略的信息
        options包含可选的请求选项

        返回:
        使用事务ID升级chaincode响应

      2. 例:
         1 c, err := New(mockClientProvider())
         2 if err != nil {
         3     fmt.Println("failed to create client")
         4 }
         5 
         6 ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
         7 req := UpgradeCCRequest{Name: "ExampleCC", Version: "v1", Path: "path", Policy: ccPolicy}
         8 
         9 resp, err := c.UpgradeCC("mychannel", req, WithTargets(mockPeer()))
        10 if err != nil {
        11     fmt.Printf("failed to upgrade chaincode: %s\n", err)
        12 }
        13 
        14 if resp.TransactionID == "" {
        15     fmt.Println("Failed to upgrade chaincode")
        16 }
        17 
        18 fmt.Println("Chaincode upgraded")
        View Code

        输出:Chaincode upgraded

  6. 类型ClientOption
    1. type ClientOption func(*Client) error: ClientOption描述了New构造函数的功能参数
    2. func WithDefaultTargetFilter(filter fab.TargetFilter) ClientOption: WithDefaultTargetFilter选项为每个客户端配置默认目标过滤器
      1. 例:
         1 ctx := mockClientProvider()
         2 
         3 c, err := New(ctx, WithDefaultTargetFilter(&urlTargetFilter{url: "example.com"}))
         4 if err != nil {
         5     fmt.Println("failed to create client")
         6 }
         7 
         8 if c != nil {
         9     fmt.Println("resource management client created with url target filter")
        10 }
        View Code

        输出:resource management client created with url target filter

  7. 类型InstallCCRequest
    1. type InstallCCRequest struct {
          Name    string
          Path    string
          Version string
          Package *resource.CCPackage
      }: InstallCCRequest包含安装链代码请求参数
  8. 类型InstallCCResponse
    1. type InstallCCResponse struct {
          Target string
          Status int32
          Info   string
      }: InstallCCResponse包含安装链代码响应状态
  9. 类型InstantiateCCRequest
    1. type InstantiateCCRequest struct {
          Name       string
          Path       string
          Version    string
          Args       [][]byte
          Policy     *common.SignaturePolicyEnvelope
          CollConfig []*common.CollectionConfig
      }:  InstantiateCCRequest包含实例化链代码请求参数 
  10. 类型InstantiateCCResponse
    1. type InstantiateCCResponse struct {
          TransactionID fab.TransactionID
      }: InstantiateCCResponse包含实例化链代码的响应参数
  11. 类型RequestOption
    1. type RequestOption func(ctx context.Client, opts *requestOptions) error: 每个Opts参数的RequestOption func
  12. func WithConfigSignatures(signatures ...*common.ConfigSignature) RequestOption: WithConfigSignatures允许为resmgmt客户端的SaveChannel调用提供预定义的签名
  13. func WithOrderer(orderer fab.Orderer) RequestOption: WithOrderer允许为请求指定orderer。
  14. func WithOrdererEndpoint(key string) RequestOption: WithOrdererEndpoint允许为请求指定orderer。 将根据关键参数查找orderer。 key参数可以是名称或url
  15. func WithParentContext(parentContext reqContext.Context) RequestOption: WithParentContext封装了grpc父上下文。
    1. 例:
       1 c, err := New(mockClientProvider())
       2 if err != nil {
       3     fmt.Println("failed to create client")
       4 }
       5 
       6 clientContext, err := mockClientProvider()()
       7 if err != nil {
       8     fmt.Println("failed to return client context")
       9     return
      10 }
      11 
      12 // get parent context and cancel
      13 parentContext, cancel := sdkCtx.NewRequest(clientContext, sdkCtx.WithTimeout(20*time.Second))
      14 defer cancel()
      15 
      16 channels, err := c.QueryChannels(WithParentContext(parentContext), WithTargets(mockPeer()))
      17 if err != nil {
      18     fmt.Printf("failed to query for blockchain info: %s\n", err)
      19 }
      20 
      21 if channels != nil {
      22     fmt.Println("Retrieved channels that peer belongs to")
      23 }
      View Code

      输出:Retrieved channels that peer belongs to

  16. func WithRetry(retryOpt retry.Opts) RequestOption: WithRetry设置重试选项。
  17. func WithTargetEndpoints(keys ...string) RequestOption: WithTargetEndpoints允许覆盖请求的目标peer。 目标由名称或URL指定,SDK将创建基础peer对象。
  18. func WithTargetFilter(targetFilter fab.TargetFilter) RequestOption: WithTargetFilter为请求启用目标过滤器。
    1. 例:
       1 c, err := New(mockClientProvider())
       2 if err != nil {
       3     fmt.Println("failed to create client")
       4 }
       5 
       6 ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
       7 req := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}
       8 
       9 resp, err := c.InstantiateCC("mychannel", req, WithTargetFilter(&urlTargetFilter{url: "http://peer1.com"}))
      10 if err != nil {
      11     fmt.Printf("failed to install chaincode: %s\n", err)
      12 }
      13 
      14 if resp.TransactionID == "" {
      15     fmt.Println("Failed to instantiate chaincode")
      16 }
      17 
      18 fmt.Println("Chaincode instantiated")
      View Code

      输出:Chaincode instantiated

  19. func WithTargets(targets ...fab.Peer) RequestOption: WithTargets允许覆盖请求的目标对等方
    1. 例:
       1 c, err := New(mockClientProvider())
       2 if err != nil {
       3     fmt.Println("failed to create client")
       4 }
       5 
       6 response, err := c.QueryChannels(WithTargets(mockPeer()))
       7 if err != nil {
       8     fmt.Printf("failed to query channels: %s\n", err)
       9 }
      10 
      11 if response != nil {
      12     fmt.Println("Retrieved channels")
      13 }
      View Code

      输出:Retrieved channels

  20. func WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption: WithTimeout封装了超时类型的键值对,如果未提供,则为Options的超时持续时间,将使用来自config的默认超时配置
  21. 类型SaveChannelRequest
    1. 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
      }: SaveChannelRequest保存保存通道请求的参数
  22. 类型SaveChannelResponse
    1. type SaveChannelResponse struct {
          TransactionID fab.TransactionID
      }: SaveChannelResponse包含保存通道的响应参数
  23. 类型UpgradeCCRequest
    1. type UpgradeCCRequest struct {
          Name       string
          Path       string
          Version    string
          Args       [][]byte
          Policy     *common.SignaturePolicyEnvelope
          CollConfig []*common.CollectionConfig
      }: UpgradeCCRequest包含升级链代码请求参数
  24. 类型UpgradeCCResponse
    1. type UpgradeCCResponse struct {
          TransactionID fab.TransactionID
      }: UpgradeCCResponse包含升级链码的响应参数
posted @ 2018-09-28 16:20  一直行走的小兵  阅读(1131)  评论(0编辑  收藏  举报