Skip to content

Commit

Permalink
Use global counters for generate port number
Browse files Browse the repository at this point in the history
Signed-off-by: Parthvi Vala <pvala@redhat.com>
  • Loading branch information
valaparthvi committed Apr 5, 2023
1 parent cb66f0c commit 861a9f4
Showing 1 changed file with 10 additions and 20 deletions.
30 changes: 10 additions & 20 deletions tests/helper/helper_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"fmt"
"github.com/redhat-developer/odo/pkg/util"
"io"
"math/rand"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"

. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -51,24 +51,14 @@ func HttpWaitForWithStatus(url string, match string, maxRetry int, interval int,
Fail(fmt.Sprintf("Failed after %d retries. Content in %s doesn't include '%s'.", maxRetry, url, match))
}

// GetRandomFreePort returns a random free port(string) between 1024 and 65535, or within a given portRange if provided
// WARN: If length of portRange is anything other than 2 and first index is greater-than-or-equal-to second index, it will use the default range.
func GetRandomFreePort(portRange ...int) string {
max := 65535
min := 1024
var (
startPort = rand.Intn(max-min) + min // #nosec // cannot use crypto/rand library here
endPort = max
)
// WARN: If length of portRange is anything other than 2 and first index is gte second index, it will be ignored
if len(portRange) == 2 && portRange[0] < portRange[1] {
startPort = portRange[0]
endPort = portRange[1]
}
freePort, err := util.NextFreePort(startPort, endPort, nil)
if err != nil {
Fail("failed to obtain a free port")
}
return strconv.Itoa(freePort)
var startPort int64 = 30000

// GetRandomFreePort increases the counter of global variable startPort, checks if the counter value is a free port, and returns.
// If the port is not free, it calls itself again. Checking the port is an additional validation to ensure we don't run into random failures because of port unavailability.
func GetRandomFreePort() string {
atomic.AddInt64(&startPort, 1)
if !util.IsPortFree(int(startPort)) {
return GetRandomFreePort()
}
return strconv.FormatInt(startPort, 10)
}

0 comments on commit 861a9f4

Please sign in to comment.