Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: pick random port instead of failing #42

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions internal/validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import (
"errors"
"fmt"
"io"
"math/rand"
"net"
"os"
"strings"
"time"
Expand Down Expand Up @@ -93,6 +95,62 @@ func Validate(image string, configPath string, cmd *cobra.Command, debug bool) (

}

// checkPorts checks if all the ports are available, if not, for each busy port
// it tries with a higher port until a valid one is found or it times out.
// If successful, it updates the validator config with the new ports
func checkPorts(validatorConfig *canaryv1.Validator) error {
found := make(chan struct{})
// hold the ports that are already in use
usedPorts := make(map[int32]struct{}, len(validatorConfig.Ports))
// Generate a random port between 1024 and 65535
getRandomPort := func() int32 {
return rand.Int31n(65535-1024) + 1024
}

for i := range validatorConfig.Ports {
port := validatorConfig.Ports[i].Port

go func() {
for {
if _, ok := usedPorts[port]; ok {
port = getRandomPort()
continue
}

if _, err := net.DialTimeout("tcp", net.JoinHostPort("", fmt.Sprintf("%d", port)), time.Second); err != nil {
if port == validatorConfig.Ports[i].Port {
usedPorts[port] = struct{}{}
found <- struct{}{}
return
}

for j := range validatorConfig.Checks {
if validatorConfig.Checks[j].Probe.HTTPGet.Port == int(validatorConfig.Ports[i].Port) {
validatorConfig.Checks[j].Probe.HTTPGet.Port = int(port)
}
}
validatorConfig.Ports[i].Port = port

usedPorts[port] = struct{}{}
found <- struct{}{}
return
}

port = getRandomPort()
}
}()

// wait for 3 seconds to connect to a valid port, fail otherwise
select {
case <-time.After(time.Second * 3):
return fmt.Errorf("could not find a valid port for %d", validatorConfig.Ports[i].Port)
case <-found:
continue
}
}
return nil
}

func loadConfig(filePath string) tea.Cmd {
return func() tea.Msg {
var validatorConfig *canaryv1.Validator
Expand All @@ -116,6 +174,13 @@ func loadConfig(filePath string) tea.Cmd {
}
}

if err = checkPorts(validatorConfig); err != nil {
return configLoaded{
Config: nil,
Error: err,
}
}

return configLoaded{
Config: validatorConfig,
Error: nil,
Expand Down