Skip to content

Instantly share code, notes, and snippets.

@aojea
Created October 8, 2021 10:18
Show Gist options
  • Select an option

  • Save aojea/07043117d3424707903f73c818a89421 to your computer and use it in GitHub Desktop.

Select an option

Save aojea/07043117d3424707903f73c818a89421 to your computer and use it in GitHub Desktop.
avoid port collision
commit adf8c8ad610f925ee424002326a68e0cca97df66 (HEAD -> test_integration_1.22)
Author: Antonio Ojea <[email protected]>
Date: Fri Oct 8 01:04:38 2021 +0200
don't get available port from the ephemeral range
diff --git a/test/integration/framework/etcd.go b/test/integration/framework/etcd.go
index aa1d36a86ab..7d2020be4e8 100644
--- a/test/integration/framework/etcd.go
+++ b/test/integration/framework/etcd.go
@@ -20,10 +20,12 @@ import (
"context"
"fmt"
"io/ioutil"
+ "math/rand"
"net"
"os"
"os/exec"
"runtime"
+ "strconv"
"strings"
"time"
@@ -49,15 +51,28 @@ func getEtcdPath() (string, error) {
}
// getAvailablePort returns a TCP port that is available for binding.
+// avoiding the ephemeral range, to avoid collisions on tests that generate
+// multiple connections. By defaylt Linux uses ports in the range 32768 - 60999
+// sysctl net.ipv4.ip_local_port_range
+// net.ipv4.ip_local_port_range = 32768 60999
func getAvailablePort() (int, error) {
- l, err := net.Listen("tcp", ":0")
- if err != nil {
- return 0, fmt.Errorf("could not bind to a port: %v", err)
+ rand.Seed(time.Now().UnixNano())
+ // get ports from the range 2048 - 8096
+ min := 2048
+ max := 8096
+ for i := min; i < max; i++ {
+ port := rand.Intn(max-min+1) + min
+ p := strconv.Itoa(port)
+ l, err := net.Listen("tcp", ":"+p)
+ if err == nil {
+ // It is possible but unlikely that someone else will bind this port before we
+ // get a chance to use it.
+ defer l.Close()
+ return l.Addr().(*net.TCPAddr).Port, nil
+ }
}
- // It is possible but unlikely that someone else will bind this port before we
- // get a chance to use it.
- defer l.Close()
- return l.Addr().(*net.TCPAddr).Port, nil
+
+ return 0, fmt.Errorf("not available port in the range %d-%d", min, max)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment