diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fdeb97..04f6fa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## vX.X.X (YYYY-MM-DD) +### Fixed +- `randomized_port_min` and `randomized_port_max` are now honored: randomized host ports were always picked from 20000-60999. Each bound still defaults (20000 and 60999) when unset; an invalid range (outside 1-65535, or a minimum above the maximum) fails startup, and a config reload with one keeps the current config +- When random picks keep colliding, a free port of the range is taken in order, so a nearly full range is still used up. When no port is left, or the port bindings store cannot be opened, the deployment fails with a clear error instead of publishing the port on an ephemeral host port outside the range + ## v0.7.1 (2026-06-02) ### Added diff --git a/config.example.yaml b/config.example.yaml index 325d57e..dbfa0b0 100755 --- a/config.example.yaml +++ b/config.example.yaml @@ -11,8 +11,8 @@ instancer: deployment_extension_window: "30m" # Time window to extend deployments before expiration (default: 30m) deployment_max_extensions: 3 # Maximum number of extensions allowed per deployment (-1 for unlimited) (default: 3) randomize_published_ports: false # TCP only: randomize host ports for non-fixed published_ports (e.g., "22" -> "34721:22") - randomized_port_min: 20000 # Lower bound for randomized host ports (default: 20000) - randomized_port_max: 60999 # Upper bound for randomized host ports (default: 60999) + randomized_port_min: 20000 # Lower bound for randomized host ports, included (default: 20000) + randomized_port_max: 60999 # Upper bound for randomized host ports, included (default: 60999) num_workers: 10 # Number of Ansible workers for processing jobs (default: 10) max_concurrent_ansible: 5 # Fallback: max concurrent Ansible when Redis not configured (default: 5) metrics: diff --git a/galvanize-instancer/internal/ansible/connection_info_test.go b/galvanize-instancer/internal/ansible/connection_info_test.go index 224ac18..793fef2 100644 --- a/galvanize-instancer/internal/ansible/connection_info_test.go +++ b/galvanize-instancer/internal/ansible/connection_info_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/28Pollux28/galvanize/pkg/config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -20,7 +21,7 @@ func TestNormalizePublishedPorts_ExtractsOptionalProtocolHints(t *testing.T) { }, } - normalized, hints, bindings := normalizePublishedPortsWithState(params, false, nil, false) + normalized, hints, bindings := normalizePublishedPortsWithState(params, false, nil, false, defaultPortRange) assert.Equal(t, "example:latest", normalized["image"]) assert.Empty(t, bindings) @@ -76,7 +77,7 @@ func TestNormalizePublishedPorts_RandomizeHostPorts_WhenEnabled(t *testing.T) { }, } - normalized, hints, bindings := normalizePublishedPortsWithState(params, true, nil, true) + normalized, hints, bindings := normalizePublishedPortsWithState(params, true, nil, true, defaultPortRange) ports, ok := normalized["published_ports"].([]interface{}) require.True(t, ok) require.Len(t, ports, 4) @@ -102,6 +103,8 @@ func TestNormalizePublishedPorts_RandomizeHostPorts_WhenEnabled(t *testing.T) { assert.NotEmpty(t, bindings) } +var defaultPortRange = portRange{lo: config.DefaultRandomizedPortMin, hi: config.DefaultRandomizedPortMax} + func isRandomBindingFor(portDef string, target string) bool { parts := strings.Split(portDef, ":") if len(parts) != 2 { @@ -114,5 +117,5 @@ func isRandomBindingFor(portDef string, target string) bool { if err != nil { return false } - return hostPort >= 20000 && hostPort <= 60999 + return defaultPortRange.contains(hostPort) } diff --git a/galvanize-instancer/internal/ansible/deployer.go b/galvanize-instancer/internal/ansible/deployer.go index f6f5305..0ebd7cd 100644 --- a/galvanize-instancer/internal/ansible/deployer.go +++ b/galvanize-instancer/internal/ansible/deployer.go @@ -42,14 +42,19 @@ func (a *AnsibleDeployer) Deploy(ctx context.Context, conf *config.Config, chall var lastErr error key := deploymentKey(chall, teamID) randomizePorts := conf.Instancer.RandomizePublishedPorts + ports := randomizedPortRange(conf) for attempt := 1; attempt <= maxRetries; attempt++ { existingBindings := loadPortBindingsFromDB(conf.Instancer.DBPath, key) if randomizePorts { randomizable := randomizableContainerPorts(chall.DeployParameters) randomizable = append(randomizable, exposeTCPContainerPorts(chall.DeployParameters)...) - existingBindings = ensureRandomPortBindingsInDB(conf.Instancer.DBPath, key, randomizable) + reserved, err := ensureRandomPortBindingsInDB(conf.Instancer.DBPath, key, randomizable, ports) + if err != nil { + return "", fmt.Errorf("failed to reserve host ports: %w", err) + } + existingBindings = reserved } - normalizedParams, protocolHints, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false) + normalizedParams, protocolHints, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false, ports) if randomizePorts { savePortBindingsToDB(conf.Instancer.DBPath, key, existingBindings) } @@ -105,7 +110,7 @@ func (a *AnsibleDeployer) Terminate(ctx context.Context, conf *config.Config, ch randomizePorts := conf.Instancer.RandomizePublishedPorts for attempt := 1; attempt <= maxRetries; attempt++ { existingBindings := loadPortBindingsFromDB(conf.Instancer.DBPath, key) - normalizedParams, _, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false) + normalizedParams, _, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false, randomizedPortRange(conf)) if _, err := applyComposeExposures(conf, chall, teamID, normalizedParams, existingBindings); err != nil { return fmt.Errorf("failed to apply compose exposures: %w", err) } diff --git a/galvanize-instancer/internal/ansible/port_bindings_store.go b/galvanize-instancer/internal/ansible/port_bindings_store.go index cd2c99f..6c32bfb 100644 --- a/galvanize-instancer/internal/ansible/port_bindings_store.go +++ b/galvanize-instancer/internal/ansible/port_bindings_store.go @@ -1,6 +1,7 @@ package ansible import ( + "fmt" "sync" "time" @@ -48,9 +49,14 @@ func loadPortBindingsFromDB(dbPath, deploymentKey string) map[string]int { return bindings } -func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts []string) map[string]int { +// ensureRandomPortBindingsInDB returns the host ports of the deployment's +// randomized container ports, reserving a free one of ports for each container +// port that has none yet. It fails when the store cannot be opened or ports +// has no free port left, rather than leaving the container port to an +// ephemeral host port outside the configured range. +func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts []string, ports portRange) (map[string]int, error) { if dbPath == "" || deploymentKey == "" || len(containerPorts) == 0 { - return map[string]int{} + return map[string]int{}, nil } portBindingDBMu.Lock() @@ -58,7 +64,7 @@ func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts [ db, err := openPortBindingDB(dbPath) if err != nil { - return map[string]int{} + return nil, fmt.Errorf("open port bindings store: %w", err) } result := map[string]int{} @@ -74,16 +80,20 @@ func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts [ continue } - hostPort := reserveRandomHostPort(db, deploymentKey, containerPort) - if hostPort > 0 { - result[containerPort] = hostPort + hostPort := reserveRandomHostPort(db, deploymentKey, containerPort, ports) + if hostPort == 0 { + return nil, fmt.Errorf("no free host port left in the randomized port range %s for container port %s", ports, containerPort) } + result[containerPort] = hostPort } - return result + return result, nil } -func reserveRandomHostPort(db *gorm.DB, deploymentKey, containerPort string) int { +// reserveRandomHostPort records a host port of ports for the container port +// and returns it, or 0 if none is free. Ports are tried at random, then in +// order, so a nearly full range is still used up. +func reserveRandomHostPort(db *gorm.DB, deploymentKey, containerPort string, ports portRange) int { if db == nil || deploymentKey == "" || containerPort == "" { return 0 } @@ -95,49 +105,54 @@ func reserveRandomHostPort(db *gorm.DB, deploymentKey, containerPort string) int } for range 128 { - hostPort := randomHostPortFromDB(db) - if hostPort == 0 { - continue - } - record := portBindingRecord{ - DeploymentKey: deploymentKey, - ContainerPort: containerPort, - HostPort: hostPort, + if hostPort := tryReserveHostPort(db, deploymentKey, containerPort, ports.random()); hostPort != 0 { + return hostPort } - res := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&record) - if res.Error != nil { + } + + // Random picks kept colliding: take the first port no binding uses + var used []int + if err := db.Model(&portBindingRecord{}).Where("host_port BETWEEN ? AND ?", ports.lo, ports.hi).Pluck("host_port", &used).Error; err != nil { + return 0 + } + taken := make(map[int]struct{}, len(used)) + for _, p := range used { + taken[p] = struct{}{} + } + for port := ports.lo; port <= ports.hi; port++ { + if _, ok := taken[port]; ok { continue } - if res.RowsAffected == 1 { + if hostPort := tryReserveHostPort(db, deploymentKey, containerPort, port); hostPort != 0 { return hostPort } - - // If insert was ignored, check whether our target mapping now exists. - var mapped portBindingRecord - if err := db.First(&mapped, "deployment_key = ? AND container_port = ?", deploymentKey, containerPort).Error; err == nil { - return mapped.HostPort - } } - return 0 } -func randomHostPortFromDB(db *gorm.DB) int { - if db == nil { +// tryReserveHostPort records hostPort for the container port unless another +// binding uses it. It returns the container port's host port, which another +// worker may have recorded meanwhile, or 0. +func tryReserveHostPort(db *gorm.DB, deploymentKey, containerPort string, hostPort int) int { + if hostPort == 0 { return 0 } - const minPort = 20000 - const maxPort = 60999 - const rangeSize = maxPort - minPort + 1 - - var hostPort int - if err := db.Raw("SELECT CAST((ABS(RANDOM()) % ?) + ? AS INTEGER)", rangeSize, minPort).Scan(&hostPort).Error; err != nil { - return 0 + record := portBindingRecord{ + DeploymentKey: deploymentKey, + ContainerPort: containerPort, + HostPort: hostPort, } - if hostPort < minPort || hostPort > maxPort { - return 0 + res := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&record) + if res.Error == nil && res.RowsAffected == 1 { + return hostPort } - return hostPort + + // If insert was ignored, check whether our target mapping now exists. + var mapped portBindingRecord + if err := db.First(&mapped, "deployment_key = ? AND container_port = ?", deploymentKey, containerPort).Error; err == nil { + return mapped.HostPort + } + return 0 } func savePortBindingsToDB(dbPath, deploymentKey string, bindings map[string]int) { diff --git a/galvanize-instancer/internal/ansible/port_range_test.go b/galvanize-instancer/internal/ansible/port_range_test.go new file mode 100644 index 0000000..0215e0b --- /dev/null +++ b/galvanize-instancer/internal/ansible/port_range_test.go @@ -0,0 +1,96 @@ +package ansible + +import ( + "fmt" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRandomizedPortRange_FromConfig(t *testing.T) { + conf := &config.Config{} + assert.Equal(t, portRange{lo: 20000, hi: 60999}, randomizedPortRange(conf), "defaults") + + conf.Instancer.RandomizedPortMin = 30000 + conf.Instancer.RandomizedPortMax = 30009 + assert.Equal(t, portRange{lo: 30000, hi: 30009}, randomizedPortRange(conf)) +} + +func TestPortRange_Random(t *testing.T) { + r := portRange{lo: 30000, hi: 30002} + seen := map[int]bool{} + for range 300 { + p := r.random() + require.True(t, r.contains(p), p) + seen[p] = true + } + assert.Len(t, seen, 3, "every port of the range is picked") + + assert.Equal(t, 40000, portRange{lo: 40000, hi: 40000}.random()) + assert.Zero(t, portRange{lo: 2, hi: 1}.random(), "empty range") +} + +func TestNormalizePublishedPorts_UsesConfiguredRange(t *testing.T) { + params := map[string]interface{}{"published_ports": []interface{}{"22", "53/udp", 443}} + r := portRange{lo: 31000, hi: 31002} + + normalized, _, bindings := normalizePublishedPortsWithState(params, true, nil, true, r) + require.Len(t, bindings, 3) + used := map[int]bool{} + for _, def := range normalized["published_ports"].([]interface{}) { + host, err := strconv.Atoi(strings.SplitN(def.(string), ":", 2)[0]) + require.NoError(t, err) + assert.True(t, r.contains(host), def) + used[host] = true + } + assert.Len(t, used, 3, "distinct host ports") +} + +func TestEnsureRandomPortBindingsInDB_UsesConfiguredRange(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "galvanize.db") + r := portRange{lo: 32000, hi: 32004} + + bindings, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team1", []string{"22", "80"}, r) + require.NoError(t, err) + require.Len(t, bindings, 2) + for _, p := range bindings { + assert.True(t, r.contains(p), p) + } + assert.NotEqual(t, bindings["22"], bindings["80"]) + + // Asking again returns the same reservation + again, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team1", []string{"22", "80"}, r) + require.NoError(t, err) + assert.Equal(t, bindings, again) +} + +func TestEnsureRandomPortBindingsInDB_FillsRangeThenFails(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "galvanize.db") + r := portRange{lo: 33000, hi: 33004} + + // Five deployments use up the five ports, the later ones through the + // in-order fallback once random picks keep colliding + used := map[int]bool{} + for i := range 5 { + b, err := ensureRandomPortBindingsInDB(dbPath, fmt.Sprintf("web/a:team%d", i), []string{"22"}, r) + require.NoError(t, err) + require.True(t, r.contains(b["22"]), b["22"]) + used[b["22"]] = true + } + assert.Len(t, used, 5) + + _, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team5", []string{"22"}, r) + require.Error(t, err) + assert.Contains(t, err.Error(), "33000-33004") + + // Freeing a deployment's bindings makes its port available again + clearPortBindingsFromDB(dbPath, "web/a:team0") + b, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team5", []string{"22"}, r) + require.NoError(t, err) + assert.True(t, r.contains(b["22"])) +} diff --git a/galvanize-instancer/internal/ansible/published_ports.go b/galvanize-instancer/internal/ansible/published_ports.go index abb8c30..b6a8dc7 100644 --- a/galvanize-instancer/internal/ansible/published_ports.go +++ b/galvanize-instancer/internal/ansible/published_ports.go @@ -2,9 +2,12 @@ package ansible import ( "crypto/rand" + "fmt" "math/big" "strconv" "strings" + + "github.com/28Pollux28/galvanize/pkg/config" ) var knownDockerProtocols = map[string]struct{}{ @@ -46,7 +49,7 @@ func randomizableContainerPorts(params map[string]interface{}) []string { // // existingBindings and resulting bindings use container port specs as keys, // for example "22", "53/udp", "8080:80". -func normalizePublishedPortsWithState(params map[string]interface{}, randomizePorts bool, existingBindings map[string]int, createState bool) (map[string]interface{}, map[int]string, map[string]int) { +func normalizePublishedPortsWithState(params map[string]interface{}, randomizePorts bool, existingBindings map[string]int, createState bool, portRng portRange) (map[string]interface{}, map[int]string, map[string]int) { normalized := make(map[string]interface{}, len(params)) for k, v := range params { normalized[k] = v @@ -78,27 +81,27 @@ func normalizePublishedPortsWithState(params map[string]interface{}, randomizePo switch v := p.(type) { case int: if randomizePorts { - normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(v), deploymentBindings, usedHostPorts, createState, &stateDirty)) + normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(v), deploymentBindings, usedHostPorts, createState, &stateDirty, portRng)) } else { normalizedPorts = append(normalizedPorts, v) } case int64: if randomizePorts { - normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.FormatInt(v, 10), deploymentBindings, usedHostPorts, createState, &stateDirty)) + normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.FormatInt(v, 10), deploymentBindings, usedHostPorts, createState, &stateDirty, portRng)) } else { normalizedPorts = append(normalizedPorts, v) } case float64: intPort := int(v) if randomizePorts { - normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(intPort), deploymentBindings, usedHostPorts, createState, &stateDirty)) + normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(intPort), deploymentBindings, usedHostPorts, createState, &stateDirty, portRng)) } else { normalizedPorts = append(normalizedPorts, intPort) } case string: composePort, targetPort, hint := splitPortHint(v) if randomizePorts && !hasExplicitHostPortMapping(composePort) { - composePort = withPersistentRandomBinding(composePort, deploymentBindings, usedHostPorts, createState, &stateDirty) + composePort = withPersistentRandomBinding(composePort, deploymentBindings, usedHostPorts, createState, &stateDirty, portRng) } normalizedPorts = append(normalizedPorts, composePort) if targetPort > 0 && hint != "" { @@ -169,9 +172,12 @@ func hasExplicitHostPortMapping(portDef string) bool { return strings.Contains(portDef, ":") } -func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}) string { +func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}, portRng portRange) string { for range 128 { - hostPort := randomHighPort() + hostPort := portRng.random() + if hostPort == 0 { + continue + } if _, used := usedHostPorts[hostPort]; used { continue } @@ -180,7 +186,7 @@ func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}) str } // Extremely unlikely fallback if random generation keeps colliding. - for port := 20000; port <= 60999; port++ { + for port := portRng.lo; port <= portRng.hi; port++ { if _, used := usedHostPorts[port]; used { continue } @@ -192,7 +198,7 @@ func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}) str return containerPort } -func withPersistentRandomBinding(containerPort string, deploymentBindings map[string]int, usedHostPorts map[int]struct{}, createState bool, stateDirty *bool) string { +func withPersistentRandomBinding(containerPort string, deploymentBindings map[string]int, usedHostPorts map[int]struct{}, createState bool, stateDirty *bool, portRng portRange) string { if deploymentBindings != nil { if existingHostPort, ok := deploymentBindings[containerPort]; ok { usedHostPorts[existingHostPort] = struct{}{} @@ -202,7 +208,7 @@ func withPersistentRandomBinding(containerPort string, deploymentBindings map[st if !createState { return containerPort } - binding := randomPortBinding(containerPort, usedHostPorts) + binding := randomPortBinding(containerPort, usedHostPorts, portRng) parts := strings.Split(binding, ":") if len(parts) == 2 && deploymentBindings != nil { hostPort, err := strconv.Atoi(parts[0]) @@ -214,14 +220,34 @@ func withPersistentRandomBinding(containerPort string, deploymentBindings map[st return binding } -func randomHighPort() int { - const minPort = 20000 - const maxPort = 60999 - const rangeSize = maxPort - minPort + 1 +// portRange is the range, bounds included, randomized host ports are +// picked from (instancer.randomized_port_min and randomized_port_max). +type portRange struct { + lo, hi int +} - v, err := rand.Int(rand.Reader, big.NewInt(rangeSize)) +func randomizedPortRange(conf *config.Config) portRange { + lo, hi := conf.Instancer.RandomizedPortRange() + return portRange{lo: lo, hi: hi} +} + +func (r portRange) contains(port int) bool { + return port >= r.lo && port <= r.hi +} + +func (r portRange) String() string { + return fmt.Sprintf("%d-%d", r.lo, r.hi) +} + +// random returns a port of the range picked at random, or 0 if the range is +// empty or the system's random source fails. +func (r portRange) random() int { + if r.lo > r.hi { + return 0 + } + v, err := rand.Int(rand.Reader, big.NewInt(int64(r.hi-r.lo+1))) if err != nil { - return minPort + return 0 } - return int(v.Int64()) + minPort + return int(v.Int64()) + r.lo } diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index c876d15..61e83e4 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "sync" "time" @@ -52,8 +53,8 @@ type InstancerConfig struct { DeploymentMaxExtensions int `mapstructure:"deployment_max_extensions,omitempty"` // Maximum number of TTL extensions allowed DeploymentExtensionWindow time.Duration `mapstructure:"deployment_extension_window,omitempty"` // Time window before expiration when extension is allowed RandomizePublishedPorts bool `mapstructure:"randomize_published_ports,omitempty"` // Randomize host ports for non-fixed TCP published_ports - RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports (default: 20000) - RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports (default: 60999) + RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports, included (default: 20000) + RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports, included (default: 60999) MaxConcurrentAnsible int `mapstructure:"max_concurrent_ansible,omitempty"` // Maximum concurrent Ansible executions (default: 5) - deprecated, use NumWorkers Redis RedisConfig `mapstructure:"redis"` // Redis configuration for job queue NumWorkers int `mapstructure:"num_workers,omitempty"` // Number of Ansible workers (default: 10) @@ -97,6 +98,36 @@ func MergeResourceLimits(defaults, overrides ResourceLimits) ResourceLimits { return result } +// Default range of randomized host ports, bounds included +const ( + DefaultRandomizedPortMin = 20000 + DefaultRandomizedPortMax = 60999 +) + +// RandomizedPortRange returns the range, bounds included, randomized host +// ports are picked from: randomized_port_min and randomized_port_max, each +// replaced by its default when unset. +func (ic InstancerConfig) RandomizedPortRange() (lo, hi int) { + lo, hi = ic.RandomizedPortMin, ic.RandomizedPortMax + if lo == 0 { + lo = DefaultRandomizedPortMin + } + if hi == 0 { + hi = DefaultRandomizedPortMax + } + return lo, hi +} + +// Validate checks the instancer settings that have no safe fallback. +func (ic InstancerConfig) Validate() error { + lo, hi := ic.RandomizedPortRange() + if lo < 1 || hi > 65535 || lo > hi { + return fmt.Errorf("invalid randomized port range %d-%d: randomized_port_min and randomized_port_max must be between 1 and 65535, the minimum not above the maximum (defaults: %d-%d)", + lo, hi, DefaultRandomizedPortMin, DefaultRandomizedPortMax) + } + return nil +} + var ( current *Config mu sync.RWMutex @@ -111,6 +142,9 @@ func Load() error { if err := viper.Unmarshal(cfg); err != nil { return err } + if err := cfg.Instancer.Validate(); err != nil { + return fmt.Errorf("instancer: %w", err) + } zap.S().Info("Config loaded successfully") current = cfg return nil diff --git a/galvanize-instancer/pkg/config/config_test.go b/galvanize-instancer/pkg/config/config_test.go new file mode 100644 index 0000000..9d80eb4 --- /dev/null +++ b/galvanize-instancer/pkg/config/config_test.go @@ -0,0 +1,56 @@ +package config + +import ( + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRandomizedPortRange_Defaults(t *testing.T) { + lo, hi := InstancerConfig{}.RandomizedPortRange() + assert.Equal(t, 20000, lo) + assert.Equal(t, 60999, hi) + + lo, hi = InstancerConfig{RandomizedPortMin: 30000}.RandomizedPortRange() + assert.Equal(t, 30000, lo) + assert.Equal(t, 60999, hi, "each bound defaults on its own") + + lo, hi = InstancerConfig{RandomizedPortMax: 25000}.RandomizedPortRange() + assert.Equal(t, 20000, lo) + assert.Equal(t, 25000, hi) +} + +func TestInstancerConfig_Validate(t *testing.T) { + for _, ok := range []InstancerConfig{ + {}, + {RandomizedPortMin: 30000, RandomizedPortMax: 30000}, + {RandomizedPortMin: 1, RandomizedPortMax: 65535}, + } { + assert.NoError(t, ok.Validate(), "%+v", ok) + } + for _, bad := range []InstancerConfig{ + {RandomizedPortMin: 40000, RandomizedPortMax: 30000}, + {RandomizedPortMin: 61000}, // above the default maximum + {RandomizedPortMax: 70000}, + {RandomizedPortMin: -1}, + } { + assert.Error(t, bad.Validate(), "%+v", bad) + } +} + +func TestLoad_RejectsInvalidPortRange(t *testing.T) { + t.Cleanup(viper.Reset) + viper.Reset() + viper.Set("instancer.randomized_port_min", 30000) + viper.Set("instancer.randomized_port_max", 30009) + require.NoError(t, Load()) + require.Equal(t, 30000, Get().Instancer.RandomizedPortMin) + + viper.Set("instancer.randomized_port_min", 40000) + err := Load() + require.Error(t, err) + assert.Contains(t, err.Error(), "randomized port range 40000-30009") + assert.Equal(t, 30000, Get().Instancer.RandomizedPortMin, "the current config is kept") +}