From ae182a7c20154c19b38f651f7276118074be7795 Mon Sep 17 00:00:00 2001 From: Adrien Delorme Date: Mon, 18 Mar 2019 13:31:51 +0100 Subject: [PATCH] qemu stepForwardSSH: use common/net pkg to find open port --- builder/qemu/step_forward_ssh.go | 49 ++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/builder/qemu/step_forward_ssh.go b/builder/qemu/step_forward_ssh.go index 6e9efaca1..b525998de 100644 --- a/builder/qemu/step_forward_ssh.go +++ b/builder/qemu/step_forward_ssh.go @@ -4,9 +4,8 @@ import ( "context" "fmt" "log" - "math/rand" - "net" + "github.com/hashicorp/packer/common/net" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" ) @@ -17,31 +16,30 @@ import ( // Uses: // // Produces: -type stepForwardSSH struct{} +type stepForwardSSH struct { + 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 { config := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", config.SSHHostPortMin, config.SSHHostPortMax) - var sshHostPort uint - - portRange := config.SSHHostPortMax - config.SSHHostPortMin + 1 - offset := uint(rand.Intn(int(portRange))) - - for { - sshHostPort = offset + config.SSHHostPortMin - log.Printf("Trying port: %d", sshHostPort) - l, err := net.Listen("tcp", fmt.Sprintf(":%d", sshHostPort)) - if err == nil { - defer l.Close() - break - } - offset++ - if offset == portRange { - offset = 0 - } + var err error + s.l, err = net.ListenRangeConfig{ + Addr: config.VNCBindAddress, + Min: config.VNCPortMin, + Max: config.VNCPortMax, + Network: "tcp", + }.Listen(ctx) + if err != nil { + err := fmt.Errorf("Error finding port: %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 ui.Say(fmt.Sprintf("Found port for communicator (SSH, WinRM, etc): %d.", sshHostPort)) // Save the port we're using so that future steps can use it @@ -50,4 +48,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) + } + } +}