2013-09-02 23:23:52 -04:00
|
|
|
package qemu
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"math/rand"
|
|
|
|
"net"
|
2014-10-03 11:14:02 -04:00
|
|
|
|
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
2013-09-02 23:23:52 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// This step adds a NAT port forwarding definition so that SSH is available
|
|
|
|
// on the guest machine.
|
|
|
|
//
|
|
|
|
// Uses:
|
|
|
|
//
|
|
|
|
// Produces:
|
|
|
|
type stepForwardSSH struct{}
|
|
|
|
|
|
|
|
func (s *stepForwardSSH) Run(state multistep.StateBag) multistep.StepAction {
|
2015-05-27 16:39:43 -04:00
|
|
|
config := state.Get("config").(*Config)
|
2013-09-02 23:23:52 -04:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
|
|
|
|
2015-09-17 07:42:58 -04:00
|
|
|
log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", config.SSHHostPortMin, config.SSHHostPortMax)
|
2013-09-02 23:23:52 -04:00
|
|
|
var sshHostPort uint
|
2014-10-03 11:14:02 -04:00
|
|
|
|
2015-09-28 23:09:38 -04:00
|
|
|
portRange := config.SSHHostPortMax - config.SSHHostPortMin + 1
|
|
|
|
offset := uint(rand.Intn(int(portRange)))
|
2014-10-03 11:14:02 -04:00
|
|
|
|
2013-09-02 23:23:52 -04:00
|
|
|
for {
|
2014-10-03 11:14:02 -04:00
|
|
|
sshHostPort = offset + config.SSHHostPortMin
|
2013-09-02 23:23:52 -04:00
|
|
|
log.Printf("Trying port: %d", sshHostPort)
|
|
|
|
l, err := net.Listen("tcp", fmt.Sprintf(":%d", sshHostPort))
|
|
|
|
if err == nil {
|
|
|
|
defer l.Close()
|
|
|
|
break
|
|
|
|
}
|
2015-04-10 17:57:32 -04:00
|
|
|
offset++
|
2015-09-28 23:09:38 -04:00
|
|
|
if offset == portRange {
|
|
|
|
offset = 0
|
|
|
|
}
|
2013-09-02 23:23:52 -04:00
|
|
|
}
|
2015-09-17 07:42:58 -04:00
|
|
|
ui.Say(fmt.Sprintf("Found port for communicator (SSH, WinRM, etc): %d.", sshHostPort))
|
2013-09-02 23:23:52 -04:00
|
|
|
|
|
|
|
// Save the port we're using so that future steps can use it
|
|
|
|
state.Put("sshHostPort", sshHostPort)
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *stepForwardSSH) Cleanup(state multistep.StateBag) {}
|