qemu stepForwardSSH: use common/net pkg to find open port

This commit is contained in:
Adrien Delorme 2019-03-18 13:31:51 +01:00
parent 446105e384
commit ae182a7c20
1 changed files with 27 additions and 22 deletions

View File

@ -4,9 +4,8 @@ import (
"context" "context"
"fmt" "fmt"
"log" "log"
"math/rand"
"net"
"github.com/hashicorp/packer/common/net"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
) )
@ -17,31 +16,30 @@ import (
// Uses: // Uses:
// //
// Produces: // 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) config := state.Get("config").(*Config)
ui := state.Get("ui").(packer.Ui) ui := state.Get("ui").(packer.Ui)
log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", config.SSHHostPortMin, config.SSHHostPortMax) log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", config.SSHHostPortMin, config.SSHHostPortMax)
var sshHostPort uint var err error
s.l, err = net.ListenRangeConfig{
portRange := config.SSHHostPortMax - config.SSHHostPortMin + 1 Addr: config.VNCBindAddress,
offset := uint(rand.Intn(int(portRange))) Min: config.VNCPortMin,
Max: config.VNCPortMax,
for { Network: "tcp",
sshHostPort = offset + config.SSHHostPortMin }.Listen(ctx)
log.Printf("Trying port: %d", sshHostPort) if err != nil {
l, err := net.Listen("tcp", fmt.Sprintf(":%d", sshHostPort)) err := fmt.Errorf("Error finding port: %s", err)
if err == nil { state.Put("error", err)
defer l.Close() ui.Error(err.Error())
break return multistep.ActionHalt
}
offset++
if offset == portRange {
offset = 0
}
} }
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)) 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 // 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 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)
}
}
}