Merge pull request #2557 from hashicorp/sethvargo/safer_server

Use a random port instead of idx in testutil
This commit is contained in:
Seth Vargo 2016-12-06 10:09:28 -08:00 committed by GitHub
commit 49dab41ed0
1 changed files with 17 additions and 13 deletions

View File

@ -23,15 +23,11 @@ import (
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
"sync/atomic"
"github.com/hashicorp/consul/consul/structs" "github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-cleanhttp"
) )
// offset is used to atomically increment the port numbers.
var offset uint64
// TestPerformanceConfig configures the performance parameters. // TestPerformanceConfig configures the performance parameters.
type TestPerformanceConfig struct { type TestPerformanceConfig struct {
RaftMultiplier uint `json:"raft_multiplier,omitempty"` RaftMultiplier uint `json:"raft_multiplier,omitempty"`
@ -82,10 +78,8 @@ type ServerConfigCallback func(c *TestServerConfig)
// defaultServerConfig returns a new TestServerConfig struct // defaultServerConfig returns a new TestServerConfig struct
// with all of the listen ports incremented by one. // with all of the listen ports incremented by one.
func defaultServerConfig() *TestServerConfig { func defaultServerConfig() *TestServerConfig {
idx := int(atomic.AddUint64(&offset, 1))
return &TestServerConfig{ return &TestServerConfig{
NodeName: fmt.Sprintf("node%d", idx), NodeName: fmt.Sprintf("node%d", randomPort()),
DisableCheckpoint: true, DisableCheckpoint: true,
Performance: &TestPerformanceConfig{ Performance: &TestPerformanceConfig{
RaftMultiplier: 1, RaftMultiplier: 1,
@ -96,16 +90,26 @@ func defaultServerConfig() *TestServerConfig {
Bind: "127.0.0.1", Bind: "127.0.0.1",
Addresses: &TestAddressConfig{}, Addresses: &TestAddressConfig{},
Ports: &TestPortConfig{ Ports: &TestPortConfig{
DNS: 20000 + idx, DNS: randomPort(),
HTTP: 21000 + idx, HTTP: randomPort(),
RPC: 22000 + idx, RPC: randomPort(),
SerfLan: 23000 + idx, SerfLan: randomPort(),
SerfWan: 24000 + idx, SerfWan: randomPort(),
Server: 25000 + idx, Server: randomPort(),
}, },
} }
} }
// randomPort asks the kernel for a random port to use.
func randomPort() int {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
// TestService is used to serialize a service definition. // TestService is used to serialize a service definition.
type TestService struct { type TestService struct {
ID string `json:",omitempty"` ID string `json:",omitempty"`