Skip to content

Commit

Permalink
修改gfconfig的配置获取方式
Browse files Browse the repository at this point in the history
  • Loading branch information
osgochina committed Jan 8, 2024
1 parent c532a2f commit 4b11192
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 52 deletions.
2 changes: 1 addition & 1 deletion dserver/cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (that *DServer) initCobra() {
// 解析debug参数
that.parserDebug(cmd.Flag("debug").Value.String() == "true")
//初始化日志配置
if e := that.initLogSetting(that.config); e != nil {
if e := that.initLogSetting(); e != nil {
cmd.PrintErrf("error:%v", e)
return
}
Expand Down
6 changes: 3 additions & 3 deletions dserver/ctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package dserver
import (
"context"
"fmt"
"github.com/gogf/gf/v2/os/gcfg"
"github.com/gogf/gf/v2/os/genv"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime"
"github.com/osgochina/dmicro/drpc"
Expand Down Expand Up @@ -192,10 +192,10 @@ func (that *Ctl) Reload(name *string) (*Result, *drpc.Status) {
func (that *Ctl) Debug(debug *bool) (*Result, *drpc.Status) {
if *debug {
logger.SetDebug(true)
_ = defaultServer.config.GetAdapter().(*gcfg.AdapterFile).Set("Debug", "true")
_ = genv.Set("DEBUG", "true")
} else {
logger.SetDebug(false)
_ = defaultServer.config.GetAdapter().(*gcfg.AdapterFile).Set("Debug", "false")
_ = genv.Set("DEBUG", "false")
}
return &Result{}, nil
}
Expand Down
23 changes: 7 additions & 16 deletions dserver/gfconf.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,21 @@ func init() {
}

// 传入配置文件地址,获取gcfg对象
func (that *DServer) getGFConf(confFile string) *gcfg.Config {
func (that *DServer) initGFConf(confFile string) {
if len(confFile) > 0 {
//指定了具体的配置文件地址
if gstr.Contains(confFile, gfile.Separator) {
confPath := gfile.Abs(confFile)
if gfile.Exists(confPath) {
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent(gfile.GetContents(confPath), gfile.Basename(confPath))
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent(gfile.GetContents(confPath), gcfg.DefaultConfigFileName)
return gcfg.Instance()
return
}
confPath = fmt.Sprintf("%s%s%s", gfile.MainPkgPath(), gfile.Separator, gfile.Basename(confPath))
if gfile.Exists(confPath) {
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent(gfile.GetContents(confPath), gfile.Basename(confPath))
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent(gfile.GetContents(confPath), gcfg.DefaultConfigFileName)
return gcfg.Instance()
return
}
} else {
// 未指定配置文件地址,但是指定了配置文件名,需要去默认的目录搜索
Expand All @@ -58,29 +58,20 @@ func (that *DServer) getGFConf(confFile string) *gcfg.Config {
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent(gfile.GetContents(confPath), gfile.Basename(confPath))
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent(gfile.GetContents(confPath), gcfg.DefaultConfigFileName)
}
return gcfg.Instance()
return
}
}
//如果环境变量有设置,则使用gf框架自带的配置文件获取流程
if customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != "" {
return gcfg.Instance()
return
}
// 如果环境变量有设置配置文件搜索路径,则使用gf框架自带的配置文件获取流程
if customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != "" {
if gfile.Exists(customPath) {
return gcfg.Instance()
return
}
}
//如果并未设置配置文件,为了让程序不报错,写入空的配置
confPath, _ := getFilePath(gcfg.DefaultConfigFileName)
if len(confPath) <= 0 {
switch g.Cfg().GetAdapter().(type) {
case *gcfg.AdapterFile:
g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetContent("{}", gfile.Basename(gcfg.DefaultConfigFileName))
default:
}
}
return gcfg.Instance()

}

// 该方法是copy自gcfg组件,在默认目录搜索配置文件
Expand Down
30 changes: 14 additions & 16 deletions dserver/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package dserver
import (
"context"
"fmt"
"github.com/gogf/gf/v2/os/gcfg"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/genv"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/glog"
Expand Down Expand Up @@ -89,25 +89,27 @@ func (that *DServer) checkStart() {

// 解析配置文件信息
func (that *DServer) parserConfig(config string) {
that.config = that.getGFConf(config)
that.initGFConf(config)
// 设置配置文件中log的配置
that.initLogCfg()
}

// 是否守护进程启动
func (that *DServer) parserDaemon(daemon bool) {
_ = that.config.GetAdapter().(*gcfg.AdapterFile).Set("Daemon", daemon)
if daemon {
_ = genv.Set("DAEMON", "true")
} else {
_ = genv.Set("DAEMON", "false")
}
}

// 解析运行环境
func (that *DServer) parserEnv(env string) {
//如果命令行传入了env参数,则使用命令行参数
if len(env) > 0 {
_ = genv.Set("ENV_NAME", gstr.ToLower(env))
_ = that.config.GetAdapter().(*gcfg.AdapterFile).Set("ENV_NAME", gstr.ToLower(env))
} else if len(that.config.MustGet(context.TODO(), "ENV_NAME").String()) <= 0 {
//如果命令行未传入env参数,且配置文件中页不存在ENV_NAME配置,则先查找环境变量ENV_NAME,并把环境变量中的ENV_NAME赋值给配置文件
_ = that.config.GetAdapter().(*gcfg.AdapterFile).Set("ENV_NAME", gstr.ToLower(genv.Get("ENV_NAME", "product").String()))
} else {
_ = genv.Set("ENV_NAME", "product")
}
}

Expand All @@ -116,30 +118,26 @@ func (that *DServer) parserDebug(debug bool) {
if debug {
// 如果启动命令行强制设置了debug参数,则优先级最高
_ = genv.Set("DEBUG", "true")
_ = that.config.GetAdapter().(*gcfg.AdapterFile).Set("Debug", true)
} else {
// 1. 从配置文件中获取debug参数,如果获取到则使用,未获取到这进行下一步
// 2. 先从环境变量获取debug参数
// 3. 最终传导获取到debug值,把它设置到配置文件中
_ = that.config.GetAdapter().(*gcfg.AdapterFile).Set("Debug", that.config.MustGet(context.TODO(), "Debug", genv.Get("DEBUG", false).Bool()).Bool())
_ = genv.Set("DEBUG", "false")
}
}

const configNodeNameLogger = "logger"

// 把配置文件中的配置信息写入到logger配置中
func (that *DServer) initLogCfg() {
if !that.config.Available(context.TODO()) {
if !g.Cfg().Available(context.TODO()) {
return
}
var m map[string]interface{}
nodeKey, _ := gutil.MapPossibleItemByKey(that.config.MustGet(context.TODO(), ".").Map(), configNodeNameLogger)
nodeKey, _ := gutil.MapPossibleItemByKey(g.Cfg().MustGet(context.TODO(), ".").Map(), configNodeNameLogger)
if nodeKey == "" {
nodeKey = configNodeNameLogger
}
m = that.config.MustGet(context.TODO(), fmt.Sprintf(`%s.%s`, nodeKey, glog.DefaultName)).Map()
m = g.Cfg().MustGet(context.TODO(), fmt.Sprintf(`%s.%s`, nodeKey, glog.DefaultName)).Map()
if len(m) == 0 {
m = that.config.MustGet(context.TODO(), nodeKey).Map()
m = g.Cfg().MustGet(context.TODO(), nodeKey).Map()
}
if len(m) > 0 {
if err := logger.SetConfigWithMap(m); err != nil {
Expand Down
23 changes: 11 additions & 12 deletions dserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ type DServer struct {
beforeStopFunc StopFunc //服务关闭之前执行该方法
pidFile string //pid文件的路径
sandboxNames *garray.StrArray // 启动服务的名称
config *gcfg.Config ///服务的配置信息
inheritAddr []InheritAddr // 多进程模式,开启平滑重启逻辑模式下需要监听的列表
procModel ProcessModel // 进程模式,processModelSingle 单进程模型,processModelMulti 多进程模型
graceful *graceful
Expand Down Expand Up @@ -106,7 +105,7 @@ func (that *DServer) ProcessModel(model ProcessModel) {
// 启动服务
func (that *DServer) run(cmd *cobra.Command) {
//判断是否是守护进程运行
if e := that.demonize(that.config); e != nil {
if e := that.demonize(); e != nil {
logger.Fatalf(context.TODO(), "error:%v", e)
}
//记录启动时间
Expand Down Expand Up @@ -228,24 +227,24 @@ func (that *DServer) searchDServiceBySandboxName(name string) (*DService, bool)

// Config 获取配置信息
func (that *DServer) Config() *gcfg.Config {
return that.config
return g.Cfg()
}

// StartTime 返回启动时间
func (that *DServer) StartTime() *gtime.Time {
return that.started
}

//通过参数设置日志级别
// 通过参数设置日志级别
// 日志级别通过环境默认分三个类型,开发环境,测试环境,生产环境
// 开发环境: 日志级别为 DEVELOP,标准输出打开
// 测试环境:日志级别为 INFO,除了debug日志,都会被打印,标准输出关闭
// 生产环境: 日志级别为 PRODUCT,会打印 WARN,ERRO,CRIT三个级别的日志,标准输出为关闭
// Debug开关会无视以上设置,强制把日志级别设置为ALL,并且打开标准输出。
func (that *DServer) initLogSetting(config *gcfg.Config) error {
loggerCfg := config.MustGet(context.TODO(), "logger")
func (that *DServer) initLogSetting() error {
loggerCfg := that.Config().MustGet(context.TODO(), "logger")
loggerCfgJson := gjson.New(loggerCfg)
env := config.MustGet(context.TODO(), "ENV_NAME").String()
env := that.Config().MustGet(context.TODO(), "ENV_NAME").String()
level := loggerCfgJson.Get("Level").String()
logger.SetDebug(false)
logger.SetStdoutPrint(false)
Expand Down Expand Up @@ -274,19 +273,19 @@ func (that *DServer) initLogSetting(config *gcfg.Config) error {
}

// 如果开启debug模式,则无视其他设置
if config.MustGet(context.TODO(), "Debug", false).Bool() {
if that.Config().MustGet(context.TODO(), "Debug", false).Bool() {
setConfig["level"] = "ALL"
setConfig["stdout"] = true
logger.SetDebug(true)
}
return logger.SetConfigWithMap(setConfig)
}

//守护进程
func (that *DServer) demonize(config *gcfg.Config) error {
// 守护进程
func (that *DServer) demonize() error {

//判断是否需要后台运行
daemon := config.MustGet(context.TODO(), "Daemon", false).Bool()
daemon := genv.Get("DAEMON", false).Bool()
if !daemon {
return nil
}
Expand Down Expand Up @@ -322,7 +321,7 @@ func (that *DServer) demonize(config *gcfg.Config) error {
return nil
}

//写入pid文件
// 写入pid文件
func (that *DServer) putPidFile() {
pid := os.Getpid()
f, e := os.OpenFile(that.pidFile, os.O_WRONLY|os.O_CREATE, os.FileMode(0600))
Expand Down
9 changes: 5 additions & 4 deletions dserver/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/genv"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gutil"
Expand Down Expand Up @@ -96,14 +97,14 @@ func (that *DService) start(cmd *cobra.Command) {
}
var args = []string{"start"}

if len(that.server.config.MustGet(context.TODO(), "ENV_NAME").String()) > 0 {
args = append(args, fmt.Sprintf("--env=%s", that.server.config.MustGet(context.TODO(), "ENV_NAME").String()))
if len(genv.Get("ENV_NAME").String()) > 0 {
args = append(args, fmt.Sprintf("--env=%s", genv.Get("ENV_NAME").String()))
}
confFile := cmd.Flag("config").Value.String()
if len(confFile) > 0 {
args = append(args, fmt.Sprintf("--config=%s", confFile))
}
if that.server.config.MustGet(context.TODO(), "Debug").Bool() {
if genv.Get("DEBUG").Bool() {
args = append(args, "--debug")
}
args = append(args, sandBoxNames...)
Expand Down Expand Up @@ -269,7 +270,7 @@ func (that *DService) makeSandBox(s ISandbox) (ISandbox, kindSandbox, error) {
iValue = cValue.Elem().FieldByName("Config")
if iValue.CanSet() {
c := &Config{}
c.Config = that.server.config
c.Config = that.server.Config()
iValue.Set(reflect.ValueOf(c))
}
_, ok = cTypeElem.FieldByName("ServiceSandbox")
Expand Down

0 comments on commit 4b11192

Please sign in to comment.