Skip to content
Closed
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 6 additions & 3 deletions galvanize-instancer/internal/ansible/connection_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"
"testing"

"github.com/28Pollux28/galvanize/pkg/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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)
}
11 changes: 8 additions & 3 deletions galvanize-instancer/internal/ansible/deployer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down
91 changes: 53 additions & 38 deletions galvanize-instancer/internal/ansible/port_bindings_store.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ansible

import (
"fmt"
"sync"
"time"

Expand Down Expand Up @@ -48,17 +49,22 @@ 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()
defer portBindingDBMu.Unlock()

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{}
Expand All @@ -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
}
Expand All @@ -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) {
Expand Down
96 changes: 96 additions & 0 deletions galvanize-instancer/internal/ansible/port_range_test.go
Original file line number Diff line number Diff line change
@@ -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"]))
}
Loading
Loading