Go入门笔记-14 EdgeX读取配置文件

读取流程如下列几张图

 

 

 

 

 

 

 

除了constant里有一个指定的configruation.poml外,这里有读取配置文件代码

github.com/edgexfoundry/go-mod-bootstrap/v2@v2.0.0/bootstrap/config/config.go

 

 

 下面是解析配置文件测试

1、首先根据提取读取配置文件的方法及结构体定义,放到一个文件中进行测试,代码如下

/*******************************************************************************
 * Copyright 2021 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 *******************************************************************************/

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/BurntSushi/toml"
	bootstrapConfig "github.com/edgexfoundry/go-mod-bootstrap/v2/config"
)

// BootStrapperInfo defines the first stage gate info
// It is the first stage gate of security bootstrapping
type BootStrapperInfo struct {
	Host      string
	StartPort int
}

// ReadyInfo defines the ready stage gate info
// It is the last stage gate of security bootstrapping for
// Kong, and all other Edgex core services
type ReadyInfo struct {
	ToRunPort int
}

// TokensInfo defines the tokens ready stage gate info
// for the secretstore setup (formerly known as vault-worker)
type TokensInfo struct {
	ReadyPort int
}

// SecretStoreSetupInfo defines the fields related to
// stage gating the secretstore setup (formerly known as vault-worker) bootstrapping
type SecretStoreSetupInfo struct {
	Host   string
	Tokens TokensInfo
}

// DatabaseInfo defines the fields related to
// stage gating the database bootstrapping
type DatabaseInfo struct {
	Host      string
	Port      int
	ReadyPort int
}

// RegistryInfo defines the fields related to
// stage gating the registry bootstrapping
type RegistryInfo struct {
	Host      string
	Port      int
	ReadyPort int
	ACL       ACLInfo
}

// ACLInfo defines the fields related to Registry's ACL process
type ACLInfo struct {
	// the protocol used for registry's API calls, usually it is different from the protocol of waitFor, i.e. TCP
	Protocol string
	// filepath to save the registry's token generated from ACL bootstrapping
	BootstrapTokenPath string
	// filepath for the secretstore's token created from secretstore-setup
	SecretsAdminTokenPath string
	// filepath for the sentinel file to indicate the registry ACL is set up successfully
	SentinelFilePath string
	// filepath to save the registry's token created for management purposes
	ManagementTokenPath string
	// the roles for registry role-based access control list
	Roles map[string]ACLRoleInfo
}

// ACLRoleInfo defines the fields related to Registry's ACL roles
type ACLRoleInfo struct {
	// the details about the role
	Description string
}

// KongDBInfo defines the fields related to
// stage gating the Kong's database bootstrapping
type KongDBInfo struct {
	Host      string
	Port      int
	ReadyPort int
}
type WaitForInfo struct {
	Timeout       string
	RetryInterval string
}

// StageGateInfo defines the gate info for the security bootstrapper
// in different stages for services. From the TOML structure perspective,
// it is segmented in the way that environment variables are easier
// to read when they become all upper cases in the environment override.
type StageGateInfo struct {
	BootStrapper     BootStrapperInfo
	Ready            ReadyInfo
	SecretStoreSetup SecretStoreSetupInfo
	Database         DatabaseInfo
	Registry         RegistryInfo
	KongDB           KongDBInfo
	WaitFor          WaitForInfo
}

type ConfigurationStruct struct {
	LogLevel    string
	StageGate   StageGateInfo
	SecretStore bootstrapConfig.SecretStoreInfo
}

// UpdateFromRaw converts configuration received from the registry to a service-specific configuration struct which is
// then used to overwrite the service's existing configuration struct.
func (c *ConfigurationStruct) UpdateFromRaw(rawConfig interface{}) bool {
	return false
}

// EmptyWritablePtr returns a pointer to a service-specific empty WritableInfo struct.  It is used by the bootstrap to
// provide the appropriate structure to registry.Client's WatchForChanges().
func (c *ConfigurationStruct) EmptyWritablePtr() interface{} {
	return nil
}

// UpdateWritableFromRaw converts configuration received from the registry to a service-specific WritableInfo struct
// which is then used to overwrite the service's existing configuration's WritableInfo struct.
func (c *ConfigurationStruct) UpdateWritableFromRaw(rawWritable interface{}) bool {
	return false
}

// GetBootstrap returns the configuration elements required by the bootstrap.  Currently, a copy of the configuration
// data is returned.  This is intended to be temporary -- since ConfigurationStruct drives the configuration.toml's
// structure -- until we can make backwards-breaking configuration.toml changes (which would consolidate these fields
// into an bootstrapConfig.BootstrapConfiguration struct contained within ConfigurationStruct).
func (c *ConfigurationStruct) GetBootstrap() bootstrapConfig.BootstrapConfiguration {
	// temporary until we can make backwards-breaking configuration.toml change
	return bootstrapConfig.BootstrapConfiguration{}
}

// GetLogLevel returns the current ConfigurationStruct's log level.
func (c *ConfigurationStruct) GetLogLevel() string {
	return c.LogLevel
}

// GetRegistryInfo returns the RegistryInfo from the ConfigurationStruct.
func (c *ConfigurationStruct) GetRegistryInfo() bootstrapConfig.RegistryInfo {
	return bootstrapConfig.RegistryInfo{}
}

// GetDatabaseInfo returns a database information map.
func (c *ConfigurationStruct) GetDatabaseInfo() map[string]bootstrapConfig.Database {
	return nil
}

// GetInsecureSecrets returns the service's InsecureSecrets.
func (c *ConfigurationStruct) GetInsecureSecrets() bootstrapConfig.InsecureSecrets {
	return nil
}

// GetRoleNames gets the slice of the keys (i.e. the service keys) from map Roles as ACL role names
func (acl ACLInfo) GetACLRoleNames() []string {
	roleNames := make([]string, 0, len(acl.Roles))
	for serviceKey := range acl.Roles {
		// always converts to lower cases by design
		roleNames = append(roleNames, strings.ToLower(serviceKey))
	}
	return roleNames
}

func main() {

	fileName := "./res/configuration.toml"
	contents, err := os.ReadFile(fileName)
	if err != nil {
		fmt.Println("could not load configuration file (%s): %s", fileName, err.Error())
		return
	}

	configuration := &ConfigurationStruct{}
	err = toml.Unmarshal(contents, configuration)
	if err != nil {
		fmt.Println("unable to parse configuration file (%s): %s", fileName, err.Error())
		return
	}
	//aa := GetBootstrap(s)
	fmt.Println(configuration)
	fmt.Println(configuration.GetLogLevel())
}

2、配置文件内容

LogLevel = 'INFO'

[StageGate]
  [StageGate.BootStrapper]
    Host = "edgex-security-bootstrapper"
    StartPort = 54321
  [StageGate.Ready]
    ToRunPort = 54329
  [StageGate.SecretStoreSetup]
    Host = "edgex-secretstore-setup"
    [StageGate.SecretStoreSetup.Tokens]
      ReadyPort = 54322
  [StageGate.Database]
    # this is intended to be the same as Database.Primary.Host/.Port for other services
    Host = "edgex-redis"
    Port = 6379
    ReadyPort = 54323
  [StageGate.Registry]
    # this is intended to be the same as Registry.Host/.Port for other services
    Host = "edgex-core-consul"
    Port = 8500
    ReadyPort = 54324
    [StageGate.Registry.ACL]
      Protocol = "http"
      # this is the filepath for the generated Consul management token from ACL bootstrap
      BootstrapTokenPath = "/tmp/edgex/secrets/consul-acl-token/bootstrap_token.json"
      # this is the filepath for the Vault token created from secretstore-setup
      SecretsAdminTokenPath = "/tmp/edgex/secrets/edgex-consul/admin/token.json"
      # this is the filepath for the sentinel file to indicate the registry ACL is set up successfully
      SentinelFilePath = "/edgex-init/consul-bootstrapper/consul_acl_done"

      # this is the filepath for the created Consul management token
      ManagementTokenPath = "/tmp/edgex/secrets/consul-acl-token/mgmt_token.json"
      
      # this section contains the list of registry roles for EdgeX services
      # the service keys are the role names
      [StageGate.Registry.ACL.Roles]
        [StageGate.Registry.ACL.Roles.app-rules-engine]
          Description = "role for application service of rules engine"
        [StageGate.Registry.ACL.Roles.core-data]
          Description = "role for coredata"
        [StageGate.Registry.ACL.Roles.core-metadata]
          Description = "role for metadata"
        [StageGate.Registry.ACL.Roles.core-command]
          Description = "role for command"
        [StageGate.Registry.ACL.Roles.support-notifications]
          Description = "role for notifications"
        [StageGate.Registry.ACL.Roles.support-scheduler]
          Description = "role for scheduler"
        [StageGate.Registry.ACL.Roles.sys-mgmt-agent]
          Description = "role for system management agent"
        [StageGate.Registry.ACL.Roles.device-virtual]
          Description = "role for device virtual service"
        [StageGate.Registry.ACL.Roles.device-rest]
          Description = "role for device rest service"
          
  [StageGate.KongDb]
    Host = "kong-db"
    Port = 5432
    ReadyPort = 54325
  [StageGate.WaitFor]
    Timeout = "10s"
    RetryInterval = "1s"

# this configuration is just part of the whole go-mod-bootstrap's secret store to have
# protocol, host, and port of secretstore using in the security-bootstrapper
# we are not really using the secret store provider from go-mod-bootstrap in the code
# also this is needed as snap does not have those environments from env-files
[SecretStore]
Type = 'vault'
Protocol = 'http'
Host = 'localhost'
Port = 8200

3、路径在./res/configuration.toml

4、运行结果

 

 

  

 

posted @ 2021-08-12 22:34  zhaogaojian  阅读(399)  评论(0编辑  收藏  举报