2013-12-24 01:27:01 -05:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2013-12-24 13:00:51 -05:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2020-05-28 16:36:45 -04:00
|
|
|
"net"
|
2013-12-24 01:27:01 -05:00
|
|
|
|
2020-11-17 19:31:03 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
|
2013-12-24 01:27:01 -05:00
|
|
|
)
|
|
|
|
|
2015-06-13 19:23:33 -04:00
|
|
|
func CommHost(config *SSHConfig) func(multistep.StateBag) (string, error) {
|
2013-12-24 13:00:51 -05:00
|
|
|
return func(state multistep.StateBag) (string, error) {
|
|
|
|
driver := state.Get("driver").(Driver)
|
2020-05-30 03:17:18 -04:00
|
|
|
comm := config.Comm
|
2013-12-24 13:00:51 -05:00
|
|
|
|
2020-06-05 13:39:12 -04:00
|
|
|
host := comm.Host()
|
|
|
|
if host != "" {
|
|
|
|
return host, nil
|
|
|
|
}
|
|
|
|
|
2020-06-04 20:04:09 -04:00
|
|
|
// Snag the port from the communicator config. This way we can use it
|
|
|
|
// to perform a 3-way handshake with all of the hosts we suspect in
|
|
|
|
// order to determine which one of the hosts is the correct one.
|
|
|
|
port := comm.Port()
|
2014-03-28 18:22:37 -04:00
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
// Get the list of potential addresses that the guest might use.
|
|
|
|
hosts, err := driver.PotentialGuestIP(state)
|
2013-12-24 13:00:51 -05:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("IP lookup failed: %s", err)
|
|
|
|
return "", fmt.Errorf("IP lookup failed: %s", err)
|
|
|
|
}
|
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
if len(hosts) == 0 {
|
2013-12-24 13:00:51 -05:00
|
|
|
log.Println("IP is blank, no IP yet.")
|
|
|
|
return "", errors.New("IP is blank")
|
|
|
|
}
|
|
|
|
|
2020-06-04 20:04:09 -04:00
|
|
|
// Iterate through our list of addresses and dial up each one similar to
|
|
|
|
// a really inefficient port-scan. This way we can determine which of
|
|
|
|
// the leases that we've parsed was the correct one and actually has our
|
|
|
|
// target ssh/winrm service bound to a tcp port.
|
2020-05-30 03:17:18 -04:00
|
|
|
for index, host := range hosts {
|
|
|
|
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port))
|
2020-05-28 16:36:45 -04:00
|
|
|
|
|
|
|
// If we got a connection, then we should be good to go. Return the
|
|
|
|
// address to the caller and pray that things work out.
|
|
|
|
if err == nil {
|
|
|
|
conn.Close()
|
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
log.Printf("Detected IP: %s", host)
|
|
|
|
return host, nil
|
2020-05-28 16:36:45 -04:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise we need to iterate to the next entry and keep hoping.
|
2020-06-04 20:04:09 -04:00
|
|
|
log.Printf("Skipping lease entry #%d due to being unable to connect to the host (%s) with tcp port (%d).", 1+index, host, port)
|
2020-05-28 16:36:45 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return "", errors.New("Host is not up")
|
2013-12-24 13:00:51 -05:00
|
|
|
}
|
|
|
|
}
|