diff --git a/packer/rpc/build.go b/packer/rpc/build.go index 910293b43..97d084809 100644 --- a/packer/rpc/build.go +++ b/packer/rpc/build.go @@ -29,6 +29,7 @@ func (b *Build) Prepare() { func (b *Build) Run(ui packer.Ui) { // Create and start the server for the UI + // TODO: Error handling server := NewServer() server.RegisterUi(ui) server.Start() diff --git a/packer/rpc/port.go b/packer/rpc/port.go new file mode 100644 index 000000000..94f9ee446 --- /dev/null +++ b/packer/rpc/port.go @@ -0,0 +1,30 @@ +package rpc + +import ( + "fmt" + "net" +) + +var portRangeMin int = 0 +var portRangeMax int = 0 + +// This sets the port range that the RPC stuff will use when creating +// new temporary servers. Some RPC calls require the creation of temporary +// RPC servers. These allow you to pick a range these bind to. +func PortRange(min, max int) { + portRangeMin = min + portRangeMax = max +} + +// This finds an open port in the given range and returns a listener +// bound to that port. +func netListenerInRange(min, max int) net.Listener { + for port := min; port <= max; port++ { + l, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err == nil { + return l + } + } + + return nil +} diff --git a/packer/rpc/port_test.go b/packer/rpc/port_test.go new file mode 100644 index 000000000..fc2a731e0 --- /dev/null +++ b/packer/rpc/port_test.go @@ -0,0 +1,30 @@ +package rpc + +import ( + "cgl.tideland.biz/asserts" + "net" + "strings" + "testing" +) + +func addrPort(address net.Addr) string { + parts := strings.Split(address.String(), ":") + return parts[len(parts) - 1] +} + +func Test_netListenerInRange(t *testing.T) { + assert := asserts.NewTestingAsserts(t, true) + + // Verify it selects an open port + L1000, err := net.Listen("tcp", ":10000") + defer L1000.Close() + assert.Nil(err, "should be able to bind to port 10000") + + L := netListenerInRange(10000, 10005) + assert.NotNil(L, "should have a listener") + assert.Equal(addrPort(L.Addr()), "10001", "should bind to open port") + + // Returns nil if there are no open ports + L = netListenerInRange(10000, 10000) + assert.Nil(L, "should not get a listener") +}