From 7783a4c027690e6e7a83d0e89d92a998882ec6e9 Mon Sep 17 00:00:00 2001 From: kaichao Date: Sun, 31 Dec 2023 14:23:50 +0800 Subject: [PATCH] fix bug in GetLocalIP(), refactor golang code. --- golang/misc/exec.go | 73 ++++++++++++++++++++++++++++++ golang/misc/file.go | 48 ++++++++++++++++++++ golang/misc/net.go | 2 +- golang/misc/util.go | 108 -------------------------------------------- 4 files changed, 122 insertions(+), 109 deletions(-) create mode 100644 golang/misc/exec.go create mode 100644 golang/misc/file.go diff --git a/golang/misc/exec.go b/golang/misc/exec.go new file mode 100644 index 0000000..a6f66b1 --- /dev/null +++ b/golang/misc/exec.go @@ -0,0 +1,73 @@ +package misc + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "os/exec" + "strings" + "time" + + "github.com/sirupsen/logrus" +) + +// ExecShellCommand ... +// +// return stdout +func ExecShellCommand(myCmd string) string { + cmd := exec.Command("bash", "-c", myCmd) + output, err := cmd.Output() + logrus.Infof("IN execCmd(), cmd=%s,stdout=%s\n", myCmd, string(output)) + if err != nil { + logrus.Errorf("ERROR in execCmd(): cmd=%s,err=%v\n", myCmd, err) + return "" + } + // remove tail \n + return strings.Replace(string(output), "\n", "", -1) +} + +// ExecShellCommandWithExitCode ... +// if timeout <= 0 then no timeout +func ExecShellCommandWithExitCode(command string, timeout int) (int, string, string) { + var cmd *exec.Cmd + if timeout > 0 { + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second) + defer cancel() + cmd = exec.CommandContext(ctx, "/bin/bash", "-c", command) + } else { + cmd = exec.Command("/bin/bash", "-c", command) + } + + var stdoutBuf, stderrBuf bytes.Buffer + cmd.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) + cmd.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) + + if err := cmd.Start(); err != nil { + errMsg := fmt.Sprintf("start command %s failed with error:%v\n", command, err) + logrus.Errorln(errMsg) + return 103, "", errMsg + } + exitCode := 0 + var errMsg string + if err := cmd.Wait(); err != nil { + if exitErr, ok := err.(*exec.ExitError); ok { + // timeout : exit_code = -1 + errMsg = fmt.Sprintf("Exit Status: %d,exit err_message:%s\ncmd:%s.\n", + exitErr.ExitCode(), exitErr.Error(), command) + logrus.Warnln(errMsg) + exitCode = exitErr.ExitCode() + if exitCode == -1 { + // timeout ! + exitCode = 100 + } + } else { + errMsg = fmt.Sprintf("wait command '%s' failed with error:%v\n", command, err) + logrus.Errorln(errMsg) + exitCode = 105 + } + } + + return exitCode, string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()) + errMsg +} diff --git a/golang/misc/file.go b/golang/misc/file.go new file mode 100644 index 0000000..034bd12 --- /dev/null +++ b/golang/misc/file.go @@ -0,0 +1,48 @@ +package misc + +import ( + "bufio" + "fmt" + "io/ioutil" + "os" + "strings" +) + +// AppendToFile ... +func AppendToFile(fileName string, line string) { + file, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) + if err != nil { + fmt.Fprintf(os.Stderr, "open file %s error,err-info:%v\n", fileName, err) + fmt.Fprintln(os.Stderr, os.Args) + os.Exit(3) + } + defer file.Close() + + writer := bufio.NewWriter(file) + writer.WriteString(line + "\n") + writer.Flush() +} + +// GetTextFileLines ... +func GetTextFileLines(textFile string) ([]string, error) { + if _, err := os.Stat(textFile); err != nil { + _, ok := err.(*os.PathError) + if ok && strings.Contains(err.Error(), "no such file or directory") { + // file not exists + return []string{}, nil + } + return []string{}, err + } + + fileContent, err := ioutil.ReadFile(textFile) + if err != nil { + return []string{}, fmt.Errorf("Read file error, filename:%s, err:%v", textFile, err) + } + var lines []string + for _, line := range strings.Split(string(fileContent), "\n") { + if strings.TrimSpace(line) != "" { + lines = append(lines, line) + } + } + return lines, nil +} diff --git a/golang/misc/net.go b/golang/misc/net.go index 7d77e94..d42a6d2 100644 --- a/golang/misc/net.go +++ b/golang/misc/net.go @@ -28,7 +28,7 @@ func GetLocalIP() string { // remove '\n' localIP = strings.Replace(localIP, "\n", "", -1) reIPv4 := regexp.MustCompile("^([0-9]+\\.){3}[0-9]+$") - if reIPv4.MatchString(localIP) { + if !reIPv4.MatchString(localIP) { logrus.Warnf("error get_local_ip, localIP=%s\n", localIP) } return localIP diff --git a/golang/misc/util.go b/golang/misc/util.go index 654dbc8..1de85ee 100644 --- a/golang/misc/util.go +++ b/golang/misc/util.go @@ -1,120 +1,12 @@ package misc import ( - "bufio" - "bytes" - "context" - "fmt" - "io" - "io/ioutil" "os" - "os/exec" "reflect" "runtime" "strings" - "time" - - "github.com/sirupsen/logrus" ) -// AppendToFile ... -func AppendToFile(fileName string, line string) { - file, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) - if err != nil { - fmt.Fprintf(os.Stderr, "open file %s error,err-info:%v\n", fileName, err) - fmt.Fprintln(os.Stderr, os.Args) - os.Exit(3) - } - defer file.Close() - - writer := bufio.NewWriter(file) - writer.WriteString(line + "\n") - writer.Flush() -} - -// ExecShellCommand ... -// -// return stdout -func ExecShellCommand(myCmd string) string { - cmd := exec.Command("bash", "-c", myCmd) - output, err := cmd.Output() - logrus.Infof("IN execCmd(), cmd=%s,stdout=%s\n", myCmd, string(output)) - if err != nil { - logrus.Errorf("ERROR in execCmd(): cmd=%s,err=%v\n", myCmd, err) - return "" - } - // 删除尾部的\n - return strings.Replace(string(output), "\n", "", -1) -} - -// ExecShellCommandWithExitCode ... -// if timeout <= 0 then no timeout -func ExecShellCommandWithExitCode(command string, timeout int) (int, string, string) { - var cmd *exec.Cmd - if timeout > 0 { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second) - defer cancel() - cmd = exec.CommandContext(ctx, "/bin/bash", "-c", command) - } else { - cmd = exec.Command("/bin/bash", "-c", command) - } - - var stdoutBuf, stderrBuf bytes.Buffer - cmd.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) - cmd.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) - - if err := cmd.Start(); err != nil { - errMsg := fmt.Sprintf("start command %s failed with error:%v\n", command, err) - logrus.Errorln(errMsg) - return 103, "", errMsg - } - exitCode := 0 - var errMsg string - if err := cmd.Wait(); err != nil { - if exitErr, ok := err.(*exec.ExitError); ok { - // timeout : exit_code = -1 - errMsg = fmt.Sprintf("Exit Status: %d,exit err_message:%s\ncmd:%s.\n", - exitErr.ExitCode(), exitErr.Error(), command) - logrus.Warnln(errMsg) - exitCode = exitErr.ExitCode() - if exitCode == -1 { - // timeout ! - exitCode = 100 - } - } else { - errMsg = fmt.Sprintf("wait command '%s' failed with error:%v\n", command, err) - logrus.Errorln(errMsg) - exitCode = 105 - } - } - - return exitCode, string(stdoutBuf.Bytes()), string(stderrBuf.Bytes()) + errMsg -} - -// GetTextFileLines ... -func GetTextFileLines(textFile string) ([]string, error) { - if _, err := os.Stat(textFile); err != nil { - _, ok := err.(*os.PathError) - if ok && strings.Contains(err.Error(), "no such file or directory") { - // file not exists - return []string{}, nil - } - return []string{}, err - } - - fileContent, err := ioutil.ReadFile(textFile) - if err != nil { - return []string{}, fmt.Errorf("Read file error, filename:%s, err:%v", textFile, err) - } - var lines []string - for _, line := range strings.Split(string(fileContent), "\n") { - if strings.TrimSpace(line) != "" { - lines = append(lines, line) - } - } - return lines, nil -} - // SplitCommaWithEscapeSupport .. func SplitCommaWithEscapeSupport(s string) []string { var ret []string