Skip to content

Commit

Permalink
Replaces IsLocalPortOpen check
Browse files Browse the repository at this point in the history
Trying to listen on the given port will instead allow us to check
against all addresses.
  • Loading branch information
claudiubelu committed Nov 29, 2024
1 parent a5ed148 commit b97b1b2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/k8s/pkg/snap/snap.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ func checkK8sServicePorts(config types.ClusterConfig, serviceConfigs types.K8sSe
if open, err := utils.IsLocalPortOpen(port); err != nil {
// Could not open port due to error.
allErrors = append(allErrors, fmt.Errorf("could not check port %s (needed by: %s): %w", port, service, err))
} else if open {
} else if !open {
allErrors = append(allErrors, fmt.Errorf("port %s (needed by: %s) is already in use.", port, service))
}
}
Expand Down
23 changes: 7 additions & 16 deletions src/k8s/pkg/utils/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,20 @@ package utils

import (
"errors"
"fmt"
"net"
"os"
"syscall"
"time"
)

// IsLocalPortOpen checks if the given local port is already open or not.
func IsLocalPortOpen(port string) (bool, error) {
if err := checkPort("localhost", port, 500*time.Millisecond); err == nil {
return true, nil
} else if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, syscall.ECONNREFUSED) {
// Without an address, Listen will listen on all addresses.
if l, err := net.Listen("tcp", fmt.Sprintf(":%s", port)); errors.Is(err, syscall.EADDRINUSE) {
return false, nil
} else {
// could not open due to error, couldn't check.
} else if err != nil {
return false, err
} else {
l.Close()
return true, nil
}
}

func checkPort(host, port string, timeout time.Duration) error {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
return err
}
conn.Close()
return nil
}

0 comments on commit b97b1b2

Please sign in to comment.