packer-plugin-xenserver/builder/xenserver/step_forward_port_over_ssh.go

69 lines
1.6 KiB
Go
Raw Normal View History

package xenserver
import (
2014-12-08 09:34:48 -06:00
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"log"
"net"
)
type stepForwardPortOverSSH struct {
2014-12-08 09:34:48 -06:00
RemotePort func(state multistep.StateBag) (uint, error)
RemoteDest func(state multistep.StateBag) (string, error)
2014-12-08 09:34:48 -06:00
HostPortMin uint
HostPortMax uint
2014-12-08 09:34:48 -06:00
ResultKey string
}
func (self *stepForwardPortOverSSH) Run(state multistep.StateBag) multistep.StepAction {
2014-12-08 09:34:48 -06:00
config := state.Get("config").(config)
ui := state.Get("ui").(packer.Ui)
2014-12-08 09:34:48 -06:00
// Find a free local port:
2014-12-08 09:34:48 -06:00
log.Printf("Looking for an available port between %d and %d",
self.HostPortMin,
self.HostPortMax)
2014-12-08 09:34:48 -06:00
var sshHostPort uint
var foundPort bool
2014-12-08 09:34:48 -06:00
foundPort = false
2014-12-08 09:34:48 -06:00
for i := self.HostPortMin; i < self.HostPortMax; i++ {
sshHostPort = i
log.Printf("Trying port: %d", sshHostPort)
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", sshHostPort))
if err == nil {
l.Close()
foundPort = true
break
}
2014-12-08 09:34:48 -06:00
}
2014-12-08 09:34:48 -06:00
if !foundPort {
log.Fatal("Error: unable to find free host port. Try providing a larger range")
return multistep.ActionHalt
}
2014-12-08 09:34:48 -06:00
ui.Say(fmt.Sprintf("Creating a local port forward over SSH on local port %d", sshHostPort))
2014-12-08 09:34:48 -06:00
remotePort, _ := self.RemotePort(state)
remoteDest, _ := self.RemoteDest(state)
2014-12-08 09:34:48 -06:00
go ssh_port_forward(sshHostPort, remotePort, remoteDest, config.HostIp, config.Username, config.Password)
ui.Say(fmt.Sprintf("Port forward setup. %d ---> %s:%d on %s", sshHostPort, remoteDest, remotePort, config.HostIp))
2014-12-08 09:34:48 -06:00
// Provide the local port to future steps.
state.Put(self.ResultKey, sshHostPort)
2014-12-08 09:34:48 -06:00
return multistep.ActionContinue
}
func (self *stepForwardPortOverSSH) Cleanup(state multistep.StateBag) {}