From 4618eda6fdc3168f080e86405701b80ec4486ede Mon Sep 17 00:00:00 2001 From: "Xinwei Xiong(cubxxw)" <3293172751nss@gmail.com> Date: Fri, 20 Oct 2023 03:49:56 +0800 Subject: [PATCH] feat: add openim flag api configpath env set Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com> --- cmd/openim-api/main.go | 2 ++ pkg/common/cmd/api.go | 3 +++ pkg/common/cmd/root.go | 52 ++++++++++++++++++++++-------------- pkg/common/config/parse.go | 54 +++++++++++++++++--------------------- 4 files changed, 61 insertions(+), 50 deletions(-) diff --git a/cmd/openim-api/main.go b/cmd/openim-api/main.go index c3ddb119d..7d06f836c 100644 --- a/cmd/openim-api/main.go +++ b/cmd/openim-api/main.go @@ -60,6 +60,8 @@ func run(port int) error { logger.Info(context.Background(), "api start init discov client") var client discoveryregistry.SvcDiscoveryRegistry + + // Determine whether zk is passed according to whether it is a clustered deployment client, err = discovery_register.NewDiscoveryRegister(config.Config.Envs.Discovery) if err != nil { logger.Error(context.Background(), "Failed to initialize discovery register", err) diff --git a/pkg/common/cmd/api.go b/pkg/common/cmd/api.go index 19b11d4b2..7ce872fac 100644 --- a/pkg/common/cmd/api.go +++ b/pkg/common/cmd/api.go @@ -28,6 +28,7 @@ type ApiCmd struct { func NewApiCmd() *ApiCmd { ret := &ApiCmd{NewRootCmd("api")} ret.SetRootCmdPt(ret) + return ret } @@ -36,11 +37,13 @@ func (a *ApiCmd) AddApi(f func(port int) error) { return f(a.getPortFlag(cmd)) } } + func (a *ApiCmd) GetPortFromConfig(portType string) int { fmt.Println("GetPortFromConfig:", portType) if portType == constant.FlagPort { return config2.Config.Api.OpenImApiPort[0] } else { + return 0 } } diff --git a/pkg/common/cmd/root.go b/pkg/common/cmd/root.go index 6973da9d6..40002d1f8 100644 --- a/pkg/common/cmd/root.go +++ b/pkg/common/cmd/root.go @@ -53,38 +53,50 @@ func WithLogName(logName string) func(*CmdOpts) { } } -func NewRootCmd(name string, opts ...func(*CmdOpts)) (rootCmd *RootCmd) { - rootCmd = &RootCmd{Name: name} - c := cobra.Command{ - Use: "start openIM application", +func NewRootCmd(name string, opts ...func(*CmdOpts)) *RootCmd { + rootCmd := &RootCmd{Name: name} + cmd := cobra.Command{ + Use: "Start openIM application", Short: fmt.Sprintf(`Start %s `, name), Long: fmt.Sprintf(`Start %s `, name), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - if err := rootCmd.getConfFromCmdAndInit(cmd); err != nil { - panic(err) - } - cmdOpts := &CmdOpts{} - for _, opt := range opts { - opt(cmdOpts) - } - if cmdOpts.loggerPrefixName == "" { - cmdOpts.loggerPrefixName = "OpenIM.log.all" - } - if err := log.InitFromConfig(cmdOpts.loggerPrefixName, name, config.Config.Log.RemainLogLevel, config.Config.Log.IsStdout, config.Config.Log.IsJson, config.Config.Log.StorageLocation, config.Config.Log.RemainRotationCount, config.Config.Log.RotationTime); err != nil { - panic(err) - } - return nil + return rootCmd.persistentPreRun(cmd, opts...) }, } - rootCmd.Command = c + rootCmd.Command = cmd rootCmd.addConfFlag() return rootCmd } + +func (rc *RootCmd) persistentPreRun(cmd *cobra.Command, opts ...func(*CmdOpts)) error { + if err := rc.getConfFromCmdAndInit(cmd); err != nil { + return fmt.Errorf("failed to get configuration from command: %w", err) + } + + cmdOpts := defaultCmdOpts() + for _, opt := range opts { + opt(cmdOpts) + } + + if err := log.InitFromConfig(cmdOpts.loggerPrefixName, rc.Name, config.Config.Log.RemainLogLevel, config.Config.Log.IsStdout, config.Config.Log.IsJson, config.Config.Log.StorageLocation, config.Config.Log.RemainRotationCount, config.Config.Log.RotationTime); err != nil { + return fmt.Errorf("failed to initialize from config: %w", err) + } + + return nil +} + +func defaultCmdOpts() *CmdOpts { + return &CmdOpts{ + loggerPrefixName: "OpenIM.log.all", + } +} + func (r *RootCmd) SetRootCmdPt(cmdItf RootCmdPt) { r.cmdItf = cmdItf } + func (r *RootCmd) addConfFlag() { - r.Command.Flags().StringP(constant.FlagConf, "c", "", "Path to config file folder") + r.Command.Flags().StringP(constant.FlagConf, "c", "", "path to config file folder") } func (r *RootCmd) AddPortFlag() { diff --git a/pkg/common/config/parse.go b/pkg/common/config/parse.go index 84cddf0da..a01884c80 100644 --- a/pkg/common/config/parse.go +++ b/pkg/common/config/parse.go @@ -21,30 +21,33 @@ import ( "path/filepath" "runtime" + "github.com/OpenIMSDK/protocol/constant" "github.com/openimsdk/open-im-server/v3/pkg/msgprocessor" - "gopkg.in/yaml.v3" - - "github.com/OpenIMSDK/protocol/constant" ) //go:embed version var Version string -var ( - _, b, _, _ = runtime.Caller(0) - // Root folder of this project. - Root = filepath.Join(filepath.Dir(b), "../../..") -) - const ( FileName = "config.yaml" NotificationFileName = "notification.yaml" DefaultFolderPath = "../config/" ) +// getProjectRoot returns the absolute path of the project root directory +func getProjectRoot() string { + // Program counter (PC): This represents the address of the function. + // File path: The full path to the source file from which the function was called. + // Line number: The line number in the source file from which the function was called. + // Success flag: it will be true if the information was successfully fetched, false otherwise. + _, b, _, _ := runtime.Caller(0) // pkg/common/config/parse.go + return filepath.Join(filepath.Dir(b), "../../..") +} + func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options { opts := msgprocessor.NewOptions() + if cfg.UnreadCount { opts = msgprocessor.WithOptions(opts, msgprocessor.WithUnreadCount(true)) } @@ -61,40 +64,31 @@ func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options { } func initConfig(config interface{}, configName, configFolderPath string) error { - if configFolderPath == "" { - configFolderPath = DefaultFolderPath - } - configPath := filepath.Join(configFolderPath, configName) - defer func() { - fmt.Println("use config", configPath) - }() - _, err := os.Stat(configPath) + configFolderPath = filepath.Join(configFolderPath, configName) + _, err := os.Stat(configFolderPath) if err != nil { if !os.IsNotExist(err) { - return err + return fmt.Errorf("stat config path error: %w", err) } - configPath = filepath.Join(Root, "config", configName) - } else { - Root = filepath.Dir(configPath) + configFolderPath = filepath.Join(getProjectRoot(), "config", configName) } - data, err := os.ReadFile(configPath) + data, err := os.ReadFile(configFolderPath) if err != nil { - return err + return fmt.Errorf("read file error: %w", err) } if err = yaml.Unmarshal(data, config); err != nil { - return err + return fmt.Errorf("unmarshal yaml error: %w", err) } + fmt.Println("use config", configFolderPath) return nil } func InitConfig(configFolderPath string) error { - err := initConfig(&Config, FileName, configFolderPath) - if err != nil { - return err + if configFolderPath == "" { + configFolderPath = DefaultFolderPath } - err = initConfig(&Config.Notification, NotificationFileName, configFolderPath) - if err != nil { + if err := initConfig(&Config, FileName, configFolderPath); err != nil { return err } - return nil + return initConfig(&Config.Notification, NotificationFileName, configFolderPath) }