Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring the option.Parse method #930

Merged
merged 4 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Prev Previous commit
The option.Parse method should return failure or success without othe…
…r logic
  • Loading branch information
godruoyi committed Feb 15, 2023
commit db9de99458320687bf66fdb65a7cec02437e8bba
13 changes: 8 additions & 5 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,18 @@ func main() {
rand.Seed(time.Now().UnixNano())

opt := option.New()
msg, err := opt.Parse()
if err != nil {
if err := opt.Parse(); err != nil {
common.Exit(1, err.Error())
}
if msg != "" {
common.Exit(0, msg)

if opt.ShowVersion {
common.Exit(0, version.Short)
}
if opt.ShowHelp {
common.Exit(0, opt.FlagUsages())
}

err = env.InitServerDir(opt)
err := env.InitServerDir(opt)
if err != nil {
log.Printf("failed to init env: %v", err)
os.Exit(1)
Expand Down
4 changes: 2 additions & 2 deletions pkg/cluster/cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func mockStaticClusterMembers(count int) ([]*option.Options, membersSlice, []*pb
opt.LogDir = "log"
opt.MemberDir = "member"
opt.Debug = false
_, err = opt.Parse() // create directories
err = opt.Parse() // create directories
if err != nil {
panic(fmt.Errorf("parse option failed: %v", err))
}
Expand Down Expand Up @@ -184,7 +184,7 @@ func createSecondaryNode(clusterName string, primaryListenPeerURLs []string) *cl
opt.Cluster.PrimaryListenPeerURLs = primaryListenPeerURLs
opt.APIAddr = fmt.Sprintf("localhost:%d", ports[0])

_, err = opt.Parse()
err = opt.Parse()
check(err)

env.InitServerDir(opt)
Expand Down
2 changes: 1 addition & 1 deletion pkg/cluster/member_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func mockTestOpt(ports []int) *option.Options {
opt.MemberDir = "member"
opt.Debug = false

if _, err := opt.Parse(); err != nil {
if err := opt.Parse(); err != nil {
panic(fmt.Errorf("parse option failed: %v", err))
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/cluster/test_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func CreateOptionsForTest(tempDir string) *option.Options {
opt.LogDir = fmt.Sprintf("%s/log", tempDir)
opt.MemberDir = fmt.Sprintf("%s/member", tempDir)

_, err = opt.Parse()
err = opt.Parse()
check(err)

env.InitServerDir(opt)
Expand Down
39 changes: 20 additions & 19 deletions pkg/option/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (

"github.com/megaease/easegress/pkg/common"
"github.com/megaease/easegress/pkg/util/codectool"
"github.com/megaease/easegress/pkg/version"
)

// ClusterOptions defines the cluster members.
Expand Down Expand Up @@ -159,7 +158,7 @@ func New() *Options {

opt.flags.IntVar(&opt.StatusUpdateMaxBatchSize, "status-update-max-batch-size", 20, "Number of object statuses to update at maximum in one transaction.")

opt.viper.BindPFlags(opt.flags)
_ = opt.viper.BindPFlags(opt.flags)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why make this change and the changes at L183, L187?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a minor update because the IDE will display a warning if we don't handle the error.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's ok, but may I know which IDE you are using? On my side, vs code never reported this warning, and this could not be a help as the error is still not handled.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm using IntelliJ IDEA, and here's an example where a warning is displayed in IntelliJ IDEA:
image


return opt
}
Expand All @@ -181,27 +180,24 @@ func (opt *Options) renameLegacyClusterRoles() {
fmtLogger := fmt.Printf // Importing logger here is an import cycle, so use fmt instead.
if opt.ClusterRole == "writer" {
opt.ClusterRole = "primary"
fmtLogger(warning, "writer", "primary")
_, _ = fmtLogger(warning, "writer", "primary")
}
if opt.ClusterRole == "reader" {
opt.ClusterRole = "secondary"
fmtLogger(warning, "reader", "secondary")
_, _ = fmtLogger(warning, "reader", "secondary")
}
}

// Parse parses all arguments, returns normal message without error if --help/--version set.
func (opt *Options) Parse() (string, error) {
// Parse parses all arguments, when the user wants to display version information or view help,
// we do not execute subsequent logic and return directly.
func (opt *Options) Parse() error {
err := opt.flags.Parse(os.Args[1:])
if err != nil {
return "", err
}

if opt.ShowVersion {
return version.Short, nil
return err
}

if opt.ShowHelp {
return opt.flags.FlagUsages(), nil
if opt.ShowVersion || opt.ShowHelp {
return nil
}

opt.viper.AutomaticEnv()
Expand All @@ -213,7 +209,7 @@ func (opt *Options) Parse() (string, error) {
opt.viper.SetConfigType("yaml")
err := opt.viper.ReadInConfig()
if err != nil {
return "", fmt.Errorf("read config file %s failed: %v",
return fmt.Errorf("read config file %s failed: %v",
opt.ConfigFile, err)
}
}
Expand All @@ -234,7 +230,7 @@ func (opt *Options) Parse() (string, error) {
c.TagName = "yaml"
})
if err != nil {
return "", fmt.Errorf("yaml file unmarshal failed, please make sure you provide valid yaml file, %v", err)
return fmt.Errorf("yaml file unmarshal failed, please make sure you provide valid yaml file, %v", err)
}

opt.renameLegacyClusterRoles()
Expand All @@ -248,25 +244,30 @@ func (opt *Options) Parse() (string, error) {

err = opt.validate()
if err != nil {
return "", err
return err
}

err = opt.prepare()
if err != nil {
return "", err
return err
}

buff, err := codectool.MarshalYAML(opt)
if err != nil {
return "", fmt.Errorf("marshal config to yaml failed: %v", err)
return fmt.Errorf("marshal config to yaml failed: %v", err)
}
opt.yamlStr = string(buff)

if opt.ShowConfig {
fmt.Printf("%s", opt.yamlStr)
}

return "", nil
return nil
}

// FlagUsages export original flag usages, see FlagSet.FlagUsages.
func (opt *Options) FlagUsages() string {
return opt.flags.FlagUsages()
}

// ParseURLs parses list of strings to url.URL objects.
Expand Down
19 changes: 6 additions & 13 deletions scripts/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

set -e

RED='\033[0;31m'
NC='\033[0m'

# First - check OS.
OS="$(uname)"
Expand All @@ -13,8 +11,7 @@ if [[ "${OS}" == "Linux" ]]; then
elif [[ "${OS}" == "Darwin" ]];then
OS=darwin
else
echo -e "Error: ${RED}Unsupport OS - ${OS}${NC}"
exit
abort "Unsupport OS - ${OS}"
fi

# Second - check the CPU arch
Expand All @@ -24,11 +21,10 @@ if [[ $ARCH == x86_64 ]]; then
ARCH=amd64
elif [[ $ARCH == i686 || $ARCH == i386 ]]; then
ARCH=386
elif [[ $ARCH == aarch64* || $ARCH == armv8* || $ARCH == arm64* ]]; then
elif [[ $ARCH == aarch64* || $ARCH == armv8* ]]; then
ARCH=arm64
else
echo -e "Error: ${RED}Unsupport CPU - ${ARCH}${NC}"
exit
abort "Unsupport CPU - ${ARCH}"
fi

# Third - download the binaries
Expand All @@ -48,7 +44,7 @@ echo "Create the directory - \"${DIR}\" successfully."
echo "Downloading the release file - \"${ARTIFACT}\" ..."
curl -sL ${ARTIFACT_URL} -o ${DIR}/${ARTIFACT}
echo "Downloaded \"${ARTIFACT}\""
tar -zxf ${DIR}/${ARTIFACT} -C "${DIR}"
tar -zxf ${DIR}/${ARTIFACT} -C easegress
echo "Extract the files successfully"

# Fourth - configure the easegress
Expand Down Expand Up @@ -83,9 +79,6 @@ if [[ "${OS}" == "linux" ]]; then
sudo systemctl start easegress

#check the status
systemctl -q is-active easegress.service && \
echo "Easegress service is running!" || \
systemctl status easegress.service
sleep 2
systemctl status easegress
fi

echo "Installed successfully"