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
|
|
|
)
|
|
|
|
|
2020-06-02 05:56:36 -04:00
|
|
|
// This step adds a NAT port forwarding definition so that SSH or WinRM is available
|
2013-09-02 23:23:52 -04:00
|
|
|
// on the guest machine.
|
2020-06-02 05:56:36 -04:00
|
|
|
type stepPortForward struct {
|
2019-03-18 08:31:51 -04:00
|
|
|
l *net.Listener
|
|
|
|
}
|
2013-09-02 23:23:52 -04:00
|
|
|
|
2020-06-02 05:56:36 -04:00
|
|
|
func (s *stepPortForward) 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)
|
|
|
|
|
2020-06-02 05:56:36 -04:00
|
|
|
commHostPort := config.CommConfig.Comm.Port()
|
|
|
|
|
|
|
|
if config.CommConfig.SkipNatMapping {
|
|
|
|
log.Printf("Skipping NAT port forwarding. Using communicator (SSH, WinRM, etc) port %d", commHostPort)
|
|
|
|
state.Put("commHostPort", commHostPort)
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", config.CommConfig.HostPortMin, config.CommConfig.HostPortMax)
|
2019-03-18 08:31:51 -04:00
|
|
|
var err error
|
|
|
|
s.l, err = net.ListenRangeConfig{
|
|
|
|
Addr: config.VNCBindAddress,
|
2020-06-02 05:56:36 -04:00
|
|
|
Min: config.CommConfig.HostPortMin,
|
|
|
|
Max: config.CommConfig.HostPortMax,
|
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
|
2020-06-02 05:56:36 -04:00
|
|
|
commHostPort = s.l.Port
|
|
|
|
ui.Say(fmt.Sprintf("Found port for communicator (SSH, WinRM, etc): %d.", commHostPort))
|
2013-09-02 23:23:52 -04:00
|
|
|
|
|
|
|
// Save the port we're using so that future steps can use it
|
2020-06-02 05:56:36 -04:00
|
|
|
state.Put("commHostPort", commHostPort)
|
2013-09-02 23:23:52 -04:00
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2020-06-02 05:56:36 -04:00
|
|
|
func (s *stepPortForward) Cleanup(state multistep.StateBag) {
|
2019-03-18 08:31:51 -04:00
|
|
|
if s.l != nil {
|
|
|
|
err := s.l.Close()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed to unlock port lockfile: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|