virtualbox StepForwardSSH: use common/net pkg to find open port

This commit is contained in:
Adrien Delorme 2019-03-15 16:51:23 +01:00
parent b5d78d47f5
commit 59370986fb
2 changed files with 30 additions and 23 deletions

View File

@ -11,8 +11,8 @@ import (
type SSHConfig struct {
Comm communicator.Config `mapstructure:",squash"`
SSHHostPortMin uint `mapstructure:"ssh_host_port_min"`
SSHHostPortMax uint `mapstructure:"ssh_host_port_max"`
SSHHostPortMin int `mapstructure:"ssh_host_port_min"`
SSHHostPortMax int `mapstructure:"ssh_host_port_max"`
SSHSkipNatMapping bool `mapstructure:"ssh_skip_nat_mapping"`
// These are deprecated, but we keep them around for BC

View File

@ -4,9 +4,8 @@ import (
"context"
"fmt"
"log"
"math/rand"
"net"
"github.com/hashicorp/packer/common/net"
"github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -23,12 +22,14 @@ import (
// Produces:
type StepForwardSSH struct {
CommConfig *communicator.Config
HostPortMin uint
HostPortMax uint
HostPortMin int
HostPortMax int
SkipNatMapping bool
l *net.Listener
}
func (s *StepForwardSSH) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepForwardSSH) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
@ -45,22 +46,21 @@ func (s *StepForwardSSH) Run(_ context.Context, state multistep.StateBag) multis
log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d",
s.HostPortMin, s.HostPortMax)
portRange := int(s.HostPortMax - s.HostPortMin + 1)
offset := rand.Intn(portRange)
for {
sshHostPort = offset + int(s.HostPortMin)
log.Printf("Trying port: %d", sshHostPort)
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", sshHostPort))
if err == nil {
defer l.Close()
break
}
offset++
if offset == portRange {
offset = 0
}
var err error
s.l, err = net.ListenRangeConfig{
Addr: "127.0.0.1",
Min: s.HostPortMin,
Max: s.HostPortMax,
Network: "tcp",
}.Listen(ctx)
if err != nil {
err := fmt.Errorf("Error creating port forwarding rule: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
s.l.Listener.Close() // free port, but don't unlock lock file
sshHostPort = s.l.Port
// Create a forwarded port mapping to the VM
ui.Say(fmt.Sprintf("Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port %d)", sshHostPort))
@ -83,4 +83,11 @@ func (s *StepForwardSSH) Run(_ context.Context, state multistep.StateBag) multis
return multistep.ActionContinue
}
func (s *StepForwardSSH) Cleanup(state multistep.StateBag) {}
func (s *StepForwardSSH) Cleanup(state multistep.StateBag) {
if s.l != nil {
err := s.l.Close()
if err != nil {
log.Printf("failed to unlock port lockfile: %v", err)
}
}
}