Skip to content

Commit

Permalink
added command and pid display when the port is busy
Browse files Browse the repository at this point in the history
  • Loading branch information
psihachina committed Oct 17, 2022
1 parent 2691708 commit 6a94b93
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions internal/commands/tunnel_up.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"regexp"
"strconv"
"strings"
"syscall"
"text/template"
)

Expand Down Expand Up @@ -379,8 +380,13 @@ func checkPort(port int) error {

l, err := net.ListenTCP("tcp", addr)
if err != nil {
logrus.Error(err)
return fmt.Errorf("port %d is not available. Please make sure there is no other process that is using the port %d", port, port)
command := fmt.Sprintf("lsof -i tcp:%d | grep LISTEN | awk '{print $1, \"(pid\", $2\")\"}'", port)
out, code := execCmd(exec.Command("bash", "-c", command))
if code == 0 {
logrus.Error(err)
return fmt.Errorf("port %d is in use by %s. Please stop the process or remove the port assigment so it will be auto-assigned", port, out)
}
return fmt.Errorf("error during run command: %s (exit code: %d)", command, code)
}

err = l.Close()
Expand Down Expand Up @@ -523,3 +529,21 @@ func setAWSCredentials(sess *session.Session) error {

return nil
}

// Execute command and return exited code.
func execCmd(cmd *exec.Cmd) (string, int) {
var waitStatus syscall.WaitStatus
out, err := cmd.Output()
if err != nil {
if err != nil {
return err.Error(), 0
}
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus = exitError.Sys().(syscall.WaitStatus)
return string(out), waitStatus.ExitStatus()
}
}

waitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)
return strings.TrimSpace(string(out)), waitStatus.ExitStatus()
}

0 comments on commit 6a94b93

Please sign in to comment.