hyperleger fabric 启动配置参数设置及获取

本文主要说明配置问题,不明白的地方,可下方留言

一、获取方式:

通过fabric1.0源码分析可知,fabric 通过viper包获取配置参数。获取路径主要为两种:

(一)环境变量

(二)core.yaml配置文件

具体实现:

(一)环境变量

从入口peer开始分析

#github.com/hyperledger/fabric/peer/main.go

const cmdRoot = "core"

func main() {
    viper.SetEnvPrefix(cmdRoot)
    viper.AutomaticEnv()
    replacer := strings.NewReplacer(".", "_")
    viper.SetEnvKeyReplacer(replacer)
    ...
}

由此可知,viper获取的变量是由core为前缀,即CORE_开头的环境变量,viper.AutomaticEnv()匹配大写的键。

环境变量配置位置,如:e2e_cli/base/peer-base.yaml

(二)配置文件

还从入口peer开始

#github.com/hyperledger/fabric/peer/main.go
#InitConfig方法初化始配置
#cmdRoot= "core"

func main() {
    ...
    err := common.InitConfig(cmdRoot)
    ...
}

#common.InitConfig方法实现
#github.com/hyperledger/fabric/peer/common/common.go


func InitConfig(cmdRoot string) error {
	config.InitViper(nil, cmdRoot)

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		return fmt.Errorf("Error when reading %s config file: %s", cmdRoot, err)
	}

	return nil
}


#config.InitViper具体实现
#github.com/hyperledger/fabric/core/config/config.go

func InitViper(v *viper.Viper, configName string) error {
	var altPath = os.Getenv("FABRIC_CFG_PATH")
	if altPath != "" {
		// If the user has overridden the path with an envvar, its the only path
		// we will consider
		addConfigPath(v, altPath)
	} else {
		// If we get here, we should use the default paths in priority order:
		//
		// *) CWD
		// *) The $GOPATH based development tree
		// *) /etc/hyperledger/fabric
		//

		// CWD
		addConfigPath(v, "./")

		// DevConfigPath
		err := AddDevConfigPath(v)
		if err != nil {
			return err
		}

		// And finally, the official path
		if dirExists(OfficialPath) {
			addConfigPath(v, OfficialPath)
		}
	}

	// Now set the configuration file.
	if v != nil {
		v.SetConfigName(configName)
	} else {
		viper.SetConfigName(configName)
	}

	return nil
}

func AddDevConfigPath(v *viper.Viper) error {
	devPath, err := GetDevConfigDir()
	if err != nil {
		return err
	}

	addConfigPath(v, devPath)

	return nil
}

func GetDevConfigDir() (string, error) {
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		return "", fmt.Errorf("GOPATH not set")
	}

	for _, p := range filepath.SplitList(gopath) {
		devPath := filepath.Join(p, "src/github.com/hyperledger/fabric/sampleconfig")
		if !dirExists(devPath) {
			continue
		}

		return devPath, nil
	}

	return "", fmt.Errorf("DevConfigDir not found in %s", gopath)
}

配置文件具体的实现到config.InitViper()方法就结束了。

由此可知,fabric配置文件首先读取环境变量FABRIC_CFG_PATH,如果FABRIC_CFG_PATH不存在,则在当前目录、开发环境目录中获取。如果未自定义配置就会使用src/github.com/hyperledger/fabric/sampleconfig目录下的core.yaml配置文件。即容器中的/etc/hyperledger/fabric

猜你喜欢

转载自blog.csdn.net/cs380637384/article/details/81390148