github.com/turingchain2020/turingchain@v1.1.21/pluginmgr/base.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package pluginmgr 插件管理模块,负责插件初始化等功能
     6  package pluginmgr
     7  
     8  import (
     9  	"github.com/turingchain2020/turingchain/rpc/types"
    10  	typ "github.com/turingchain2020/turingchain/types"
    11  	wcom "github.com/turingchain2020/turingchain/wallet/common"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  // PluginBase plugin module base struct
    16  type PluginBase struct {
    17  	Name     string
    18  	ExecName string
    19  	RPC      func(name string, s types.RPCServer)
    20  	Exec     func(name string, cfg *typ.TuringchainConfig, sub []byte)
    21  	Wallet   func(walletBiz wcom.WalletOperate, sub []byte)
    22  	Cmd      func() *cobra.Command
    23  }
    24  
    25  // GetName 获取整个插件的包名,用以计算唯一值、做前缀等
    26  func (p *PluginBase) GetName() string {
    27  	return p.Name
    28  }
    29  
    30  // GetExecutorName 获取插件中执行器名
    31  func (p *PluginBase) GetExecutorName() string {
    32  	return p.ExecName
    33  }
    34  
    35  // InitExec init exec
    36  func (p *PluginBase) InitExec(cfg *typ.TuringchainConfig) {
    37  	sub := cfg.GetSubConfig().Exec
    38  	subcfg, ok := sub[p.ExecName]
    39  	if !ok {
    40  		subcfg = nil
    41  	}
    42  	p.Exec(p.ExecName, cfg, subcfg)
    43  }
    44  
    45  // InitWallet init wallet plugin
    46  func (p *PluginBase) InitWallet(walletBiz wcom.WalletOperate, sub map[string][]byte) {
    47  	subcfg, ok := sub[p.ExecName]
    48  	if !ok {
    49  		subcfg = nil
    50  	}
    51  	p.Wallet(walletBiz, subcfg)
    52  }
    53  
    54  // AddCmd add Command for plugin cli
    55  func (p *PluginBase) AddCmd(rootCmd *cobra.Command) {
    56  	if p.Cmd != nil {
    57  		cmd := p.Cmd()
    58  		if cmd == nil {
    59  			return
    60  		}
    61  		rootCmd.AddCommand(cmd)
    62  	}
    63  }
    64  
    65  // AddRPC add Rpc for plugin
    66  func (p *PluginBase) AddRPC(c types.RPCServer) {
    67  	if p.RPC != nil {
    68  		p.RPC(p.GetExecutorName(), c)
    69  	}
    70  }