2013-09-02 22:23:52 -05:00
|
|
|
package qemu
|
|
|
|
|
|
|
|
import (
|
2018-01-22 15:32:33 -08:00
|
|
|
"context"
|
2013-09-02 22:23:52 -05:00
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"math/rand"
|
|
|
|
"net"
|
2014-10-03 10:14:02 -05:00
|
|
|
|
2018-01-19 16:18:44 -08:00
|
|
|
"github.com/hashicorp/packer/helper/multistep"
|
2017-04-04 13:39:01 -07:00
|
|
|
"github.com/hashicorp/packer/packer"
|
2013-09-02 22:23:52 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// This step adds a NAT port forwarding definition so that SSH is available
|
|
|
|
// on the guest machine.
|
|
|
|
//
|
|
|
|
// Uses:
|
|
|
|
//
|
|
|
|
// Produces:
|
|
|
|
type stepForwardSSH struct{}
|
|
|
|
|
2018-01-22 15:31:41 -08:00
|
|
|
func (s *stepForwardSSH) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
|
2015-05-27 13:39:43 -07:00
|
|
|
config := state.Get("config").(*Config)
|
2013-09-02 22:23:52 -05:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
|
|
|
|
2015-09-17 13:42:58 +02:00
|
|
|
log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", config.SSHHostPortMin, config.SSHHostPortMax)
|
2013-09-02 22:23:52 -05:00
|
|
|
var sshHostPort uint
|
2014-10-03 10:14:02 -05:00
|
|
|
|
2015-09-29 03:09:38 +00:00
|
|
|
portRange := config.SSHHostPortMax - config.SSHHostPortMin + 1
|
|
|
|
offset := uint(rand.Intn(int(portRange)))
|
2014-10-03 10:14:02 -05:00
|
|
|
|
2013-09-02 22:23:52 -05:00
|
|
|
for {
|
2014-10-03 10:14:02 -05:00
|
|
|
sshHostPort = offset + config.SSHHostPortMin
|
2013-09-02 22:23:52 -05: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 14:57:32 -07:00
|
|
|
offset++
|
2015-09-29 03:09:38 +00:00
|
|
|
if offset == portRange {
|
|
|
|
offset = 0
|
|
|
|
}
|
2013-09-02 22:23:52 -05:00
|
|
|
}
|
2015-09-17 13:42:58 +02:00
|
|
|
ui.Say(fmt.Sprintf("Found port for communicator (SSH, WinRM, etc): %d.", sshHostPort))
|
2013-09-02 22:23:52 -05: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) {}
|