2013-09-02 23:23:52 -04:00
|
|
|
package qemu
|
|
|
|
|
|
|
|
import (
|
2018-01-22 18:32:33 -05:00
|
|
|
"context"
|
2013-09-02 23:23:52 -04:00
|
|
|
"fmt"
|
|
|
|
"log"
|
2014-10-03 11:14:02 -04:00
|
|
|
|
2019-03-18 08:31:51 -04:00
|
|
|
"github.com/hashicorp/packer/common/net"
|
2018-01-19 19:18:44 -05:00
|
|
|
"github.com/hashicorp/packer/helper/multistep"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/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:
|
2019-03-18 08:31:51 -04:00
|
|
|
type stepForwardSSH struct {
|
|
|
|
l *net.Listener
|
|
|
|
}
|
2013-09-02 23:23:52 -04:00
|
|
|
|
2019-03-18 08:31:51 -04:00
|
|
|
func (s *stepForwardSSH) Run(ctx context.Context, 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)
|
2019-03-18 08:31:51 -04:00
|
|
|
var err error
|
|
|
|
s.l, err = net.ListenRangeConfig{
|
|
|
|
Addr: config.VNCBindAddress,
|
2019-05-06 18:01:09 -04:00
|
|
|
Min: config.SSHHostPortMin,
|
|
|
|
Max: config.SSHHostPortMax,
|
2019-03-18 08:31:51 -04:00
|
|
|
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
|
2013-09-02 23:23:52 -04:00
|
|
|
}
|
2019-03-18 08:31:51 -04:00
|
|
|
s.l.Listener.Close() // free port, but don't unlock lock file
|
|
|
|
sshHostPort := s.l.Port
|
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
|
|
|
|
}
|
|
|
|
|
2019-03-18 08:31:51 -04:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|