Skip to content

Commit

Permalink
Merge pull request #504 from hazelops/IZE-524-ize-tunnel-when-port-is…
Browse files Browse the repository at this point in the history
…-occupied-show-which-process-uses-it-and-suggest-to-kill-it

IZE-524 added command and pid display when the port is busy
  • Loading branch information
psihachina authored Oct 24, 2022
2 parents 0a66861 + a5a4ffc commit cbe4fae
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions internal/commands/tunnel_up.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"text/template"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2instanceconnect"
Expand All @@ -17,17 +29,6 @@ import (
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"text/template"
)

const sshConfig = `# SSH over Session Manager
Expand Down Expand Up @@ -410,8 +411,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)
stdout, stderr, code, err := term.New(term.WithStdout(io.Discard), term.WithStderr(io.Discard)).Run(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, strings.TrimSpace(stdout))
}
return fmt.Errorf("error during run command: %s (exit code: %d, stderr: %s)", command, code, stderr)
}

err = l.Close()
Expand Down

0 comments on commit cbe4fae

Please sign in to comment.