go fmt on builder/vmware/*

This commit is contained in:
Ali Rizvi-Santiago 2017-02-27 15:34:53 -06:00
parent 0d6cf7fac4
commit 884af69da1
8 changed files with 1075 additions and 833 deletions

View File

@ -1,19 +1,19 @@
package common package common
import ( import (
"errors"
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"net"
"os" "os"
"os/exec" "os/exec"
"io/ioutil"
"regexp" "regexp"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"net"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
) )
@ -214,23 +214,27 @@ func compareVersions(versionFound string, versionWanted string, product string)
/// helper functions that read configuration information from a file /// helper functions that read configuration information from a file
// read the network<->device configuration out of the specified path // read the network<->device configuration out of the specified path
func ReadNetmapConfig(path string) (NetworkMap,error) { func ReadNetmapConfig(path string) (NetworkMap, error) {
fd,err := os.Open(path) fd, err := os.Open(path)
if err != nil { return nil, err } if err != nil {
return nil, err
}
defer fd.Close() defer fd.Close()
return ReadNetworkMap(fd) return ReadNetworkMap(fd)
} }
// read the dhcp configuration out of the specified path // read the dhcp configuration out of the specified path
func ReadDhcpConfig(path string) (DhcpConfiguration,error) { func ReadDhcpConfig(path string) (DhcpConfiguration, error) {
fd,err := os.Open(path) fd, err := os.Open(path)
if err != nil { return nil, err } if err != nil {
return nil, err
}
defer fd.Close() defer fd.Close()
return ReadDhcpConfiguration(fd) return ReadDhcpConfiguration(fd)
} }
// read the VMX configuration from the specified path // read the VMX configuration from the specified path
func readVMXConfig(path string) (map[string]string,error) { func readVMXConfig(path string) (map[string]string, error) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
return map[string]string{}, err return map[string]string{}, err
@ -245,7 +249,7 @@ func readVMXConfig(path string) (map[string]string,error) {
} }
// read the connection type out of a vmx configuration // read the connection type out of a vmx configuration
func readCustomDeviceName(vmxData map[string]string) (string,error) { func readCustomDeviceName(vmxData map[string]string) (string, error) {
connectionType, ok := vmxData["ethernet0.connectiontype"] connectionType, ok := vmxData["ethernet0.connectiontype"]
if !ok || connectionType != "custom" { if !ok || connectionType != "custom" {
@ -272,12 +276,14 @@ type VmwareDriver struct {
NetmapConfPath func() string NetmapConfPath func() string
} }
func (d *VmwareDriver) GuestAddress(state multistep.StateBag) (string,error) { func (d *VmwareDriver) GuestAddress(state multistep.StateBag) (string, error) {
vmxPath := state.Get("vmx_path").(string) vmxPath := state.Get("vmx_path").(string)
log.Println("Lookup up IP information...") log.Println("Lookup up IP information...")
vmxData, err := readVMXConfig(vmxPath) vmxData, err := readVMXConfig(vmxPath)
if err != nil { return "", err } if err != nil {
return "", err
}
var ok bool var ok bool
macAddress := "" macAddress := ""
@ -287,40 +293,50 @@ func (d *VmwareDriver) GuestAddress(state multistep.StateBag) (string,error) {
} }
} }
res,err := net.ParseMAC(macAddress) res, err := net.ParseMAC(macAddress)
if err != nil { return "", err } if err != nil {
return "", err
}
return res.String(),nil return res.String(), nil
} }
func (d *VmwareDriver) GuestIP(state multistep.StateBag) (string,error) { func (d *VmwareDriver) GuestIP(state multistep.StateBag) (string, error) {
// read netmap config // read netmap config
pathNetmap := d.NetmapConfPath() pathNetmap := d.NetmapConfPath()
if _, err := os.Stat(pathNetmap); err != nil { if _, err := os.Stat(pathNetmap); err != nil {
return "", fmt.Errorf("Could not find netmap conf file: %s", pathNetmap) return "", fmt.Errorf("Could not find netmap conf file: %s", pathNetmap)
} }
netmap,err := ReadNetmapConfig(pathNetmap) netmap, err := ReadNetmapConfig(pathNetmap)
if err != nil { return "",err } if err != nil {
return "", err
}
// convert the stashed network to a device // convert the stashed network to a device
network := state.Get("vmnetwork").(string) network := state.Get("vmnetwork").(string)
device,err := netmap.NameIntoDevice(network) device, err := netmap.NameIntoDevice(network)
// we were unable to find the device, maybe it's a custom one... // we were unable to find the device, maybe it's a custom one...
// so, check to see if it's in the .vmx configuration // so, check to see if it's in the .vmx configuration
if err != nil || network == "custom" { if err != nil || network == "custom" {
vmxPath := state.Get("vmx_path").(string) vmxPath := state.Get("vmx_path").(string)
vmxData, err := readVMXConfig(vmxPath) vmxData, err := readVMXConfig(vmxPath)
if err != nil { return "", err } if err != nil {
return "", err
}
device, err = readCustomDeviceName(vmxData) device, err = readCustomDeviceName(vmxData)
if err != nil { return "", err } if err != nil {
return "", err
}
} }
// figure out our MAC address for looking up the guest address // figure out our MAC address for looking up the guest address
MACAddress,err := d.GuestAddress(state) MACAddress, err := d.GuestAddress(state)
if err != nil { return "", err } if err != nil {
return "", err
}
// figure out the correct dhcp leases // figure out the correct dhcp leases
dhcpLeasesPath := d.DhcpLeasesPath(device) dhcpLeasesPath := d.DhcpLeasesPath(device)
@ -382,29 +398,35 @@ func (d *VmwareDriver) GuestIP(state multistep.StateBag) (string,error) {
return curIp, nil return curIp, nil
} }
func (d *VmwareDriver) HostAddress(state multistep.StateBag) (string,error) { func (d *VmwareDriver) HostAddress(state multistep.StateBag) (string, error) {
// parse network<->device mapping // parse network<->device mapping
pathNetmap := d.NetmapConfPath() pathNetmap := d.NetmapConfPath()
if _, err := os.Stat(pathNetmap); err != nil { if _, err := os.Stat(pathNetmap); err != nil {
return "", fmt.Errorf("Could not find netmap conf file: %s", pathNetmap) return "", fmt.Errorf("Could not find netmap conf file: %s", pathNetmap)
} }
netmap,err := ReadNetmapConfig(pathNetmap) netmap, err := ReadNetmapConfig(pathNetmap)
if err != nil { return "",err } if err != nil {
return "", err
}
// convert network to name // convert network to name
network := state.Get("vmnetwork").(string) network := state.Get("vmnetwork").(string)
device,err := netmap.NameIntoDevice(network) device, err := netmap.NameIntoDevice(network)
// we were unable to find the device, maybe it's a custom one... // we were unable to find the device, maybe it's a custom one...
// so, check to see if it's in the .vmx configuration // so, check to see if it's in the .vmx configuration
if err != nil || network == "custom" { if err != nil || network == "custom" {
vmxPath := state.Get("vmx_path").(string) vmxPath := state.Get("vmx_path").(string)
vmxData, err := readVMXConfig(vmxPath) vmxData, err := readVMXConfig(vmxPath)
if err != nil { return "", err } if err != nil {
return "", err
}
device, err = readCustomDeviceName(vmxData) device, err = readCustomDeviceName(vmxData)
if err != nil { return "", err } if err != nil {
return "", err
}
} }
// parse dhcpd configuration // parse dhcpd configuration
@ -413,54 +435,68 @@ func (d *VmwareDriver) HostAddress(state multistep.StateBag) (string,error) {
return "", fmt.Errorf("Could not find vmnetdhcp conf file: %s", pathDhcpConfig) return "", fmt.Errorf("Could not find vmnetdhcp conf file: %s", pathDhcpConfig)
} }
config,err := ReadDhcpConfig(pathDhcpConfig) config, err := ReadDhcpConfig(pathDhcpConfig)
if err != nil { return "",err } if err != nil {
return "", err
}
// find the entry configured in the dhcpd // find the entry configured in the dhcpd
interfaceConfig,err := config.HostByName(device) interfaceConfig, err := config.HostByName(device)
if err != nil { return "", err } if err != nil {
return "", err
}
// finally grab the hardware address // finally grab the hardware address
address,err := interfaceConfig.Hardware() address, err := interfaceConfig.Hardware()
if err == nil { return address.String(), nil } if err == nil {
return address.String(), nil
}
// we didn't find it, so search through our interfaces for the device name // we didn't find it, so search through our interfaces for the device name
interfaceList,err := net.Interfaces() interfaceList, err := net.Interfaces()
if err == nil { return "", err } if err == nil {
return "", err
}
names := make([]string, 0) names := make([]string, 0)
for _,intf := range interfaceList { for _, intf := range interfaceList {
if strings.HasSuffix( strings.ToLower(intf.Name), device ) { if strings.HasSuffix(strings.ToLower(intf.Name), device) {
return intf.HardwareAddr.String(),nil return intf.HardwareAddr.String(), nil
} }
names = append(names, intf.Name) names = append(names, intf.Name)
} }
return "",fmt.Errorf("Unable to find device %s : %v", device, names) return "", fmt.Errorf("Unable to find device %s : %v", device, names)
} }
func (d *VmwareDriver) HostIP(state multistep.StateBag) (string,error) { func (d *VmwareDriver) HostIP(state multistep.StateBag) (string, error) {
// parse network<->device mapping // parse network<->device mapping
pathNetmap := d.NetmapConfPath() pathNetmap := d.NetmapConfPath()
if _, err := os.Stat(pathNetmap); err != nil { if _, err := os.Stat(pathNetmap); err != nil {
return "", fmt.Errorf("Could not find netmap conf file: %s", pathNetmap) return "", fmt.Errorf("Could not find netmap conf file: %s", pathNetmap)
} }
netmap,err := ReadNetmapConfig(pathNetmap) netmap, err := ReadNetmapConfig(pathNetmap)
if err != nil { return "",err } if err != nil {
return "", err
}
// convert network to name // convert network to name
network := state.Get("vmnetwork").(string) network := state.Get("vmnetwork").(string)
device,err := netmap.NameIntoDevice(network) device, err := netmap.NameIntoDevice(network)
// we were unable to find the device, maybe it's a custom one... // we were unable to find the device, maybe it's a custom one...
// so, check to see if it's in the .vmx configuration // so, check to see if it's in the .vmx configuration
if err != nil || network == "custom" { if err != nil || network == "custom" {
vmxPath := state.Get("vmx_path").(string) vmxPath := state.Get("vmx_path").(string)
vmxData, err := readVMXConfig(vmxPath) vmxData, err := readVMXConfig(vmxPath)
if err != nil { return "", err } if err != nil {
return "", err
}
device, err = readCustomDeviceName(vmxData) device, err = readCustomDeviceName(vmxData)
if err != nil { return "", err } if err != nil {
return "", err
}
} }
// parse dhcpd configuration // parse dhcpd configuration
@ -468,15 +504,21 @@ func (d *VmwareDriver) HostIP(state multistep.StateBag) (string,error) {
if _, err := os.Stat(pathDhcpConfig); err != nil { if _, err := os.Stat(pathDhcpConfig); err != nil {
return "", fmt.Errorf("Could not find vmnetdhcp conf file: %s", pathDhcpConfig) return "", fmt.Errorf("Could not find vmnetdhcp conf file: %s", pathDhcpConfig)
} }
config,err := ReadDhcpConfig(pathDhcpConfig) config, err := ReadDhcpConfig(pathDhcpConfig)
if err != nil { return "",err } if err != nil {
return "", err
}
// find the entry configured in the dhcpd // find the entry configured in the dhcpd
interfaceConfig,err := config.HostByName(device) interfaceConfig, err := config.HostByName(device)
if err != nil { return "", err } if err != nil {
return "", err
}
address,err := interfaceConfig.IP4() address, err := interfaceConfig.IP4()
if err != nil { return "", err } if err != nil {
return "", err
}
return address.String(),nil return address.String(), nil
} }

File diff suppressed because it is too large Load Diff

View File

@ -8,9 +8,9 @@ import (
"fmt" "fmt"
"log" "log"
"os/exec" "os/exec"
"path/filepath"
"regexp" "regexp"
"runtime" "runtime"
"path/filepath"
) )
func playerFindVdiskManager() (string, error) { func playerFindVdiskManager() (string, error) {

View File

@ -33,4 +33,3 @@ func (d *Workstation10Driver) Verify() error {
return workstationVerifyVersion(VMWARE_WS_VERSION) return workstationVerifyVersion(VMWARE_WS_VERSION)
} }

View File

@ -62,15 +62,12 @@ type Config struct {
Parallel string `mapstructure:"parallel"` Parallel string `mapstructure:"parallel"`
// booting a guest // booting a guest
BootCommand []string `mapstructure:"boot_command"`
KeepRegistered bool `mapstructure:"keep_registered"` KeepRegistered bool `mapstructure:"keep_registered"`
OVFToolOptions []string `mapstructure:"ovftool_options"` OVFToolOptions []string `mapstructure:"ovftool_options"`
SkipCompaction bool `mapstructure:"skip_compaction"` SkipCompaction bool `mapstructure:"skip_compaction"`
SkipExport bool `mapstructure:"skip_export"` SkipExport bool `mapstructure:"skip_export"`
VMName string `mapstructure:"vm_name"`
VMXDiskTemplatePath string `mapstructure:"vmx_disk_template_path"` VMXDiskTemplatePath string `mapstructure:"vmx_disk_template_path"`
VMXTemplatePath string `mapstructure:"vmx_template_path"` VMXTemplatePath string `mapstructure:"vmx_template_path"`
Version string `mapstructure:"version"`
// remote vsphere // remote vsphere
RemoteType string `mapstructure:"remote_type"` RemoteType string `mapstructure:"remote_type"`

View File

@ -6,6 +6,7 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
vmwcommon "github.com/hashicorp/packer/builder/vmware/common" vmwcommon "github.com/hashicorp/packer/builder/vmware/common"
@ -90,7 +91,7 @@ type serialUnion struct {
auto *serialConfigAuto auto *serialConfigAuto
} }
func unformat_serial(config string) (*serialUnion,error) { func unformat_serial(config string) (*serialUnion, error) {
var defaultSerialPort string var defaultSerialPort string
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
defaultSerialPort = "COM1" defaultSerialPort = "COM1"
@ -100,7 +101,7 @@ func unformat_serial(config string) (*serialUnion,error) {
input := strings.SplitN(config, ":", 2) input := strings.SplitN(config, ":", 2)
if len(input) < 1 { if len(input) < 1 {
return nil,fmt.Errorf("Unexpected format for serial port: %s", config) return nil, fmt.Errorf("Unexpected format for serial port: %s", config)
} }
var formatType, formatOptions string var formatType, formatOptions string
@ -115,58 +116,58 @@ func unformat_serial(config string) (*serialUnion,error) {
case "PIPE": case "PIPE":
comp := strings.Split(formatOptions, ",") comp := strings.Split(formatOptions, ",")
if len(comp) < 3 || len(comp) > 4 { if len(comp) < 3 || len(comp) > 4 {
return nil,fmt.Errorf("Unexpected format for serial port : pipe : %s", config) return nil, fmt.Errorf("Unexpected format for serial port : pipe : %s", config)
} }
if res := strings.ToLower(comp[1]); res != "client" && res != "server" { if res := strings.ToLower(comp[1]); res != "client" && res != "server" {
return nil,fmt.Errorf("Unexpected format for serial port : pipe : endpoint : %s : %s", res, config) return nil, fmt.Errorf("Unexpected format for serial port : pipe : endpoint : %s : %s", res, config)
} }
if res := strings.ToLower(comp[2]); res != "app" && res != "vm" { if res := strings.ToLower(comp[2]); res != "app" && res != "vm" {
return nil,fmt.Errorf("Unexpected format for serial port : pipe : host : %s : %s", res, config) return nil, fmt.Errorf("Unexpected format for serial port : pipe : host : %s : %s", res, config)
} }
res := &serialConfigPipe{ res := &serialConfigPipe{
filename : comp[0], filename: comp[0],
endpoint : comp[1], endpoint: comp[1],
host : map[string]string{"app":"TRUE","vm":"FALSE"}[strings.ToLower(comp[2])], host: map[string]string{"app": "TRUE", "vm": "FALSE"}[strings.ToLower(comp[2])],
yield : "FALSE", yield: "FALSE",
} }
if len(comp) == 4 { if len(comp) == 4 {
res.yield = strings.ToUpper(comp[3]) res.yield = strings.ToUpper(comp[3])
} }
if res.yield != "TRUE" && res.yield != "FALSE" { if res.yield != "TRUE" && res.yield != "FALSE" {
return nil,fmt.Errorf("Unexpected format for serial port : pipe : yield : %s : %s", res.yield, config) return nil, fmt.Errorf("Unexpected format for serial port : pipe : yield : %s : %s", res.yield, config)
} }
return &serialUnion{serialType:res, pipe:res},nil return &serialUnion{serialType: res, pipe: res}, nil
case "FILE": case "FILE":
comp := strings.Split(formatOptions, ",") comp := strings.Split(formatOptions, ",")
if len(comp) > 2 { if len(comp) > 2 {
return nil,fmt.Errorf("Unexpected format for serial port : file : %s", config) return nil, fmt.Errorf("Unexpected format for serial port : file : %s", config)
} }
res := &serialConfigFile{ yield : "FALSE" } res := &serialConfigFile{yield: "FALSE"}
res.filename = filepath.FromSlash(comp[0]) res.filename = filepath.FromSlash(comp[0])
res.yield = map[bool]string{true:strings.ToUpper(comp[0]), false:"FALSE"}[len(comp) > 1] res.yield = map[bool]string{true: strings.ToUpper(comp[0]), false: "FALSE"}[len(comp) > 1]
if res.yield != "TRUE" && res.yield != "FALSE" { if res.yield != "TRUE" && res.yield != "FALSE" {
return nil,fmt.Errorf("Unexpected format for serial port : file : yield : %s : %s", res.yield, config) return nil, fmt.Errorf("Unexpected format for serial port : file : yield : %s : %s", res.yield, config)
} }
return &serialUnion{serialType:res, file:res},nil return &serialUnion{serialType: res, file: res}, nil
case "DEVICE": case "DEVICE":
comp := strings.Split(formatOptions, ",") comp := strings.Split(formatOptions, ",")
if len(comp) > 2 { if len(comp) > 2 {
return nil,fmt.Errorf("Unexpected format for serial port : device : %s", config) return nil, fmt.Errorf("Unexpected format for serial port : device : %s", config)
} }
res := new(serialConfigDevice) res := new(serialConfigDevice)
if len(comp) == 2 { if len(comp) == 2 {
res.devicename = map[bool]string{true:filepath.FromSlash(comp[0]), false:defaultSerialPort}[len(comp[0]) > 0] res.devicename = map[bool]string{true: filepath.FromSlash(comp[0]), false: defaultSerialPort}[len(comp[0]) > 0]
res.yield = strings.ToUpper(comp[1]) res.yield = strings.ToUpper(comp[1])
} else if len(comp) == 1 { } else if len(comp) == 1 {
res.devicename = map[bool]string{true:filepath.FromSlash(comp[0]), false:defaultSerialPort}[len(comp[0]) > 0] res.devicename = map[bool]string{true: filepath.FromSlash(comp[0]), false: defaultSerialPort}[len(comp[0]) > 0]
res.yield = "FALSE" res.yield = "FALSE"
} else if len(comp) == 0 { } else if len(comp) == 0 {
res.devicename = defaultSerialPort res.devicename = defaultSerialPort
@ -174,10 +175,10 @@ func unformat_serial(config string) (*serialUnion,error) {
} }
if res.yield != "TRUE" && res.yield != "FALSE" { if res.yield != "TRUE" && res.yield != "FALSE" {
return nil,fmt.Errorf("Unexpected format for serial port : device : yield : %s : %s", res.yield, config) return nil, fmt.Errorf("Unexpected format for serial port : device : yield : %s : %s", res.yield, config)
} }
return &serialUnion{serialType:res, device:res},nil return &serialUnion{serialType: res, device: res}, nil
case "AUTO": case "AUTO":
res := new(serialConfigAuto) res := new(serialConfigAuto)
@ -190,13 +191,13 @@ func unformat_serial(config string) (*serialUnion,error) {
} }
if res.yield != "TRUE" && res.yield != "FALSE" { if res.yield != "TRUE" && res.yield != "FALSE" {
return nil,fmt.Errorf("Unexpected format for serial port : auto : yield : %s : %s", res.yield, config) return nil, fmt.Errorf("Unexpected format for serial port : auto : yield : %s : %s", res.yield, config)
} }
return &serialUnion{serialType:res, auto:res},nil return &serialUnion{serialType: res, auto: res}, nil
default: default:
return nil,fmt.Errorf("Unknown serial type : %s : %s", strings.ToUpper(formatType), config) return nil, fmt.Errorf("Unknown serial type : %s : %s", strings.ToUpper(formatType), config)
} }
} }
@ -218,10 +219,10 @@ type parallelPortAuto struct {
bidirectional string bidirectional string
} }
func unformat_parallel(config string) (*parallelUnion,error) { func unformat_parallel(config string) (*parallelUnion, error) {
input := strings.SplitN(config, ":", 2) input := strings.SplitN(config, ":", 2)
if len(input) < 1 { if len(input) < 1 {
return nil,fmt.Errorf("Unexpected format for parallel port: %s", config) return nil, fmt.Errorf("Unexpected format for parallel port: %s", config)
} }
var formatType, formatOptions string var formatType, formatOptions string
@ -234,38 +235,43 @@ func unformat_parallel(config string) (*parallelUnion,error) {
switch strings.ToUpper(formatType) { switch strings.ToUpper(formatType) {
case "FILE": case "FILE":
res := &parallelPortFile{ filename: filepath.FromSlash(formatOptions) } res := &parallelPortFile{filename: filepath.FromSlash(formatOptions)}
return &parallelUnion{ parallelType:res, file: res},nil return &parallelUnion{parallelType: res, file: res}, nil
case "DEVICE": case "DEVICE":
comp := strings.Split(formatOptions, ",") comp := strings.Split(formatOptions, ",")
if len(comp) < 1 || len(comp) > 2 { if len(comp) < 1 || len(comp) > 2 {
return nil,fmt.Errorf("Unexpected format for parallel port: %s", config) return nil, fmt.Errorf("Unexpected format for parallel port: %s", config)
} }
res := new(parallelPortDevice) res := new(parallelPortDevice)
res.bidirectional = "FALSE" res.bidirectional = "FALSE"
res.devicename = strings.ToUpper(comp[0]) res.devicename = filepath.FromSlash(comp[0])
if len(comp) > 1 { if len(comp) > 1 {
switch strings.ToUpper(comp[1]) { switch strings.ToUpper(comp[1]) {
case "BI": res.bidirectional = "TRUE" case "BI":
case "UNI": res.bidirectional = "FALSE" res.bidirectional = "TRUE"
case "UNI":
res.bidirectional = "FALSE"
default: default:
return nil,fmt.Errorf("Unknown parallel port direction : %s : %s", strings.ToUpper(comp[0]), config) return nil, fmt.Errorf("Unknown parallel port direction : %s : %s", strings.ToUpper(comp[0]), config)
} }
} }
return &parallelUnion{ parallelType:res, device:res },nil return &parallelUnion{parallelType: res, device: res}, nil
case "AUTO": case "AUTO":
res := new(parallelPortAuto) res := new(parallelPortAuto)
switch strings.ToUpper(formatOptions) { switch strings.ToUpper(formatOptions) {
case "": fallthrough case "":
case "UNI": res.bidirectional = "FALSE" fallthrough
case "BI": res.bidirectional = "TRUE" case "UNI":
res.bidirectional = "FALSE"
case "BI":
res.bidirectional = "TRUE"
default: default:
return nil,fmt.Errorf("Unknown parallel port direction : %s : %s", strings.ToUpper(formatOptions), config) return nil, fmt.Errorf("Unknown parallel port direction : %s : %s", strings.ToUpper(formatOptions), config)
} }
return &parallelUnion{ parallelType:res, auto:res },nil return &parallelUnion{parallelType: res, auto: res}, nil
} }
return nil,fmt.Errorf("Unexpected format for parallel port: %s", config) return nil, fmt.Errorf("Unexpected format for parallel port: %s", config)
} }
/* regular steps */ /* regular steps */
@ -348,8 +354,8 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
Version: config.Version, Version: config.Version,
ISOPath: isoPath, ISOPath: isoPath,
Sound_Present: map[bool]string{true:"TRUE",false:"FALSE"}[bool(config.Sound)], Sound_Present: map[bool]string{true: "TRUE", false: "FALSE"}[bool(config.Sound)],
Usb_Present: map[bool]string{true:"TRUE",false:"FALSE"}[bool(config.USB)], Usb_Present: map[bool]string{true: "TRUE", false: "FALSE"}[bool(config.USB)],
Serial_Present: "FALSE", Serial_Present: "FALSE",
Parallel_Present: "FALSE", Parallel_Present: "FALSE",
@ -367,7 +373,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
ui.Error(err.Error()) ui.Error(err.Error())
return multistep.ActionHalt return multistep.ActionHalt
} }
netmap,res := vmwcommon.ReadNetmapConfig(pathNetmap) netmap, res := vmwcommon.ReadNetmapConfig(pathNetmap)
if res != nil { if res != nil {
err := fmt.Errorf("Unable to read netmap conf file: %s: %v", pathNetmap, res) err := fmt.Errorf("Unable to read netmap conf file: %s: %v", pathNetmap, res)
state.Put("error", err) state.Put("error", err)
@ -376,7 +382,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
} }
// try and convert the specified network to a device // try and convert the specified network to a device
device,err := netmap.NameIntoDevice(network) device, err := netmap.NameIntoDevice(network)
// success. so we know that it's an actual network type inside netmap.conf // success. so we know that it's an actual network type inside netmap.conf
if err == nil { if err == nil {
@ -392,7 +398,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
/// check if serial port has been configured /// check if serial port has been configured
if config.Serial != "" { if config.Serial != "" {
serial,err := unformat_serial(config.Serial) serial, err := unformat_serial(config.Serial)
if err != nil { if err != nil {
err := fmt.Errorf("Error procesing VMX template: %s", err) err := fmt.Errorf("Error procesing VMX template: %s", err)
state.Put("error", err) state.Put("error", err)
@ -436,7 +442,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
/// check if parallel port has been configured /// check if parallel port has been configured
if config.Parallel != "" { if config.Parallel != "" {
parallel,err := unformat_parallel(config.Parallel) parallel, err := unformat_parallel(config.Parallel)
if err != nil { if err != nil {
err := fmt.Errorf("Error procesing VMX template: %s", err) err := fmt.Errorf("Error procesing VMX template: %s", err)
state.Put("error", err) state.Put("error", err)

View File

@ -1,21 +1,21 @@
package iso package iso
import ( import (
"bytes"
"fmt" "fmt"
"os" "io/ioutil"
"path/filepath"
"strings"
"math" "math"
"math/rand" "math/rand"
"strconv" "os"
"io/ioutil" "path/filepath"
"bytes"
"runtime" "runtime"
"strconv"
"strings"
"testing"
"github.com/mitchellh/packer/packer" "github.com/mitchellh/packer/packer"
"github.com/mitchellh/packer/template"
"github.com/mitchellh/packer/provisioner/shell" "github.com/mitchellh/packer/provisioner/shell"
"github.com/mitchellh/packer/template"
"testing"
) )
var vmxTestBuilderConfig = map[string]string{ var vmxTestBuilderConfig = map[string]string{
@ -46,18 +46,20 @@ func tmpnam(prefix string) string {
dir := os.TempDir() dir := os.TempDir()
max := int(math.Pow(2, float64(length))) max := int(math.Pow(2, float64(length)))
n,err := rand.Intn(max),nil n, err := rand.Intn(max), nil
for path = filepath.Join(dir, prefix + strconv.Itoa(n)); err == nil; _,err = os.Stat(path) { for path = filepath.Join(dir, prefix+strconv.Itoa(n)); err == nil; _, err = os.Stat(path) {
n = rand.Intn(max) n = rand.Intn(max)
path = filepath.Join(dir, prefix + strconv.Itoa(n)) path = filepath.Join(dir, prefix+strconv.Itoa(n))
} }
return path return path
} }
func createFloppyOutput(prefix string) (string,string,error) { func createFloppyOutput(prefix string) (string, string, error) {
output := tmpnam(prefix) output := tmpnam(prefix)
f,err := os.Create(output) f, err := os.Create(output)
if err != nil { return "","",fmt.Errorf("Unable to create empty %s: %s", output, err) } if err != nil {
return "", "", fmt.Errorf("Unable to create empty %s: %s", output, err)
}
f.Close() f.Close()
vmxData := []string{ vmxData := []string{
@ -69,18 +71,24 @@ func createFloppyOutput(prefix string) (string,string,error) {
} }
outputFile := strings.Replace(output, "\\", "\\\\", -1) outputFile := strings.Replace(output, "\\", "\\\\", -1)
vmxString := fmt.Sprintf("{" + strings.Join(vmxData, ",") + "}", outputFile) vmxString := fmt.Sprintf("{"+strings.Join(vmxData, ",")+"}", outputFile)
return output,vmxString,nil return output, vmxString, nil
} }
func readFloppyOutput(path string) (string,error) { func readFloppyOutput(path string) (string, error) {
f,err := os.Open(path) f, err := os.Open(path)
if err != nil { return "",fmt.Errorf("Unable to open file %s", path) } if err != nil {
return "", fmt.Errorf("Unable to open file %s", path)
}
defer f.Close() defer f.Close()
data,err := ioutil.ReadAll(f) data, err := ioutil.ReadAll(f)
if err != nil { return "",fmt.Errorf("Unable to read file: %s", err) } if err != nil {
if len(data) == 0 { return "", nil } return "", fmt.Errorf("Unable to read file: %s", err)
return string(data[:bytes.IndexByte(data,0)]),nil }
if len(data) == 0 {
return "", nil
}
return string(data[:bytes.IndexByte(data, 0)]), nil
} }
func setupVMwareBuild(t *testing.T, builderConfig map[string]string, provisionerConfig map[string]string) error { func setupVMwareBuild(t *testing.T, builderConfig map[string]string, provisionerConfig map[string]string) error {
@ -88,47 +96,55 @@ func setupVMwareBuild(t *testing.T, builderConfig map[string]string, provisioner
// create builder config and update with user-supplied options // create builder config and update with user-supplied options
cfgBuilder := map[string]string{} cfgBuilder := map[string]string{}
for k,v := range vmxTestBuilderConfig { cfgBuilder[k] = v } for k, v := range vmxTestBuilderConfig {
for k,v := range builderConfig { cfgBuilder[k] = v } cfgBuilder[k] = v
}
for k, v := range builderConfig {
cfgBuilder[k] = v
}
// convert our builder config into a single sprintfable string // convert our builder config into a single sprintfable string
builderLines := []string{} builderLines := []string{}
for k,v := range cfgBuilder { for k, v := range cfgBuilder {
builderLines = append(builderLines, fmt.Sprintf(`"%s":%s`, k, v)) builderLines = append(builderLines, fmt.Sprintf(`"%s":%s`, k, v))
} }
// create provisioner config and update with user-supplied options // create provisioner config and update with user-supplied options
cfgProvisioner := map[string]string{} cfgProvisioner := map[string]string{}
for k,v := range vmxTestProvisionerConfig { cfgProvisioner[k] = v } for k, v := range vmxTestProvisionerConfig {
for k,v := range provisionerConfig { cfgProvisioner[k] = v } cfgProvisioner[k] = v
}
for k, v := range provisionerConfig {
cfgProvisioner[k] = v
}
// convert our provisioner config into a single sprintfable string // convert our provisioner config into a single sprintfable string
provisionerLines := []string{} provisionerLines := []string{}
for k,v := range cfgProvisioner { for k, v := range cfgProvisioner {
provisionerLines = append(provisionerLines, fmt.Sprintf(`"%s":%s`, k, v)) provisionerLines = append(provisionerLines, fmt.Sprintf(`"%s":%s`, k, v))
} }
// and now parse them into a template // and now parse them into a template
configString := fmt.Sprintf(vmxTestTemplate, strings.Join(builderLines,`,`), strings.Join(provisionerLines,`,`)) configString := fmt.Sprintf(vmxTestTemplate, strings.Join(builderLines, `,`), strings.Join(provisionerLines, `,`))
tpl,err := template.Parse(strings.NewReader(configString)) tpl, err := template.Parse(strings.NewReader(configString))
if err != nil { if err != nil {
t.Fatalf("Unable to parse test config: %s", err) t.Fatalf("Unable to parse test config: %s", err)
} }
// create our config to test the vmware-iso builder // create our config to test the vmware-iso builder
components := packer.ComponentFinder{ components := packer.ComponentFinder{
Builder: func(n string) (packer.Builder,error) { Builder: func(n string) (packer.Builder, error) {
return &Builder{},nil return &Builder{}, nil
}, },
Hook: func(n string) (packer.Hook,error) { Hook: func(n string) (packer.Hook, error) {
return &packer.DispatchHook{},nil return &packer.DispatchHook{}, nil
}, },
PostProcessor: func(n string) (packer.PostProcessor,error) { PostProcessor: func(n string) (packer.PostProcessor, error) {
return &packer.MockPostProcessor{},nil return &packer.MockPostProcessor{}, nil
}, },
Provisioner: func(n string) (packer.Provisioner,error) { Provisioner: func(n string) (packer.Provisioner, error) {
return &shell.Provisioner{},nil return &shell.Provisioner{}, nil
}, },
} }
config := packer.CoreConfig{ config := packer.CoreConfig{
@ -137,23 +153,27 @@ func setupVMwareBuild(t *testing.T, builderConfig map[string]string, provisioner
} }
// create a core using our template // create a core using our template
core,err := packer.NewCore(&config) core, err := packer.NewCore(&config)
if err != nil { t.Fatalf("Unable to create core: %s", err) } if err != nil {
t.Fatalf("Unable to create core: %s", err)
}
// now we can prepare our build // now we can prepare our build
b,err := core.Build("vmware-iso") b, err := core.Build("vmware-iso")
if err != nil { t.Fatalf("Unable to create build: %s", err) } if err != nil {
t.Fatalf("Unable to create build: %s", err)
}
warn,err := b.Prepare() warn, err := b.Prepare()
if len(warn) > 0 { if len(warn) > 0 {
for _,w := range warn { for _, w := range warn {
t.Logf("Configuration warning: %s", w) t.Logf("Configuration warning: %s", w)
} }
} }
// and then finally build it // and then finally build it
cache := &packer.FileCache{CacheDir: os.TempDir()} cache := &packer.FileCache{CacheDir: os.TempDir()}
artifacts,err := b.Run(ui, cache) artifacts, err := b.Run(ui, cache)
if err != nil { if err != nil {
t.Fatalf("Failed to build artifact: %s", err) t.Fatalf("Failed to build artifact: %s", err)
} }
@ -166,7 +186,7 @@ func setupVMwareBuild(t *testing.T, builderConfig map[string]string, provisioner
// otherwise some number of errors happened // otherwise some number of errors happened
t.Logf("Unexpected number of artifacts returned: %d", len(artifacts)) t.Logf("Unexpected number of artifacts returned: %d", len(artifacts))
errors := make([]error, 0) errors := make([]error, 0)
for _,artifact := range artifacts { for _, artifact := range artifacts {
if err := artifact.Destroy(); err != nil { if err := artifact.Destroy(); err != nil {
errors = append(errors, err) errors = append(errors, err)
} }
@ -186,9 +206,11 @@ func TestStepCreateVmx_SerialFile(t *testing.T) {
} }
error := setupVMwareBuild(t, serialConfig, map[string]string{}) error := setupVMwareBuild(t, serialConfig, map[string]string{})
if error != nil { t.Errorf("Unable to read file: %s", error) } if error != nil {
t.Errorf("Unable to read file: %s", error)
}
f,err := os.Stat(tmpfile) f, err := os.Stat(tmpfile)
if err != nil { if err != nil {
t.Errorf("VMware builder did not create a file for serial port: %s", err) t.Errorf("VMware builder did not create a file for serial port: %s", err)
} }
@ -216,19 +238,29 @@ func TestStepCreateVmx_SerialPort(t *testing.T) {
} }
// where to write output // where to write output
output,vmxData,err := createFloppyOutput("SerialPortOutput.") output, vmxData, err := createFloppyOutput("SerialPortOutput.")
if err != nil { t.Fatalf("Error creating output: %s", err) } if err != nil {
defer func() { if _,err := os.Stat(output); err == nil { os.Remove(output) } }() t.Fatalf("Error creating output: %s", err)
}
defer func() {
if _, err := os.Stat(output); err == nil {
os.Remove(output)
}
}()
config["vmx_data"] = vmxData config["vmx_data"] = vmxData
t.Logf("Preparing to write output to %s", output) t.Logf("Preparing to write output to %s", output)
// whee // whee
err = setupVMwareBuild(t, config, provision) err = setupVMwareBuild(t, config, provision)
if err != nil { t.Errorf("%s", err) } if err != nil {
t.Errorf("%s", err)
}
// check the output // check the output
data,err := readFloppyOutput(output) data, err := readFloppyOutput(output)
if err != nil { t.Errorf("%s", err) } if err != nil {
t.Errorf("%s", err)
}
if data != "serial8250: ttyS1 at\n" { if data != "serial8250: ttyS1 at\n" {
t.Errorf("Serial port not detected : %v", data) t.Errorf("Serial port not detected : %v", data)
@ -251,19 +283,29 @@ func TestStepCreateVmx_ParallelPort(t *testing.T) {
} }
// where to write output // where to write output
output,vmxData,err := createFloppyOutput("ParallelPortOutput.") output, vmxData, err := createFloppyOutput("ParallelPortOutput.")
if err != nil { t.Fatalf("Error creating output: %s", err) } if err != nil {
defer func() { if _,err := os.Stat(output); err == nil { os.Remove(output) } }() t.Fatalf("Error creating output: %s", err)
}
defer func() {
if _, err := os.Stat(output); err == nil {
os.Remove(output)
}
}()
config["vmx_data"] = vmxData config["vmx_data"] = vmxData
t.Logf("Preparing to write output to %s", output) t.Logf("Preparing to write output to %s", output)
// whee // whee
error := setupVMwareBuild(t, config, provision) error := setupVMwareBuild(t, config, provision)
if error != nil { t.Errorf("%s", error) } if error != nil {
t.Errorf("%s", error)
}
// check the output // check the output
data,err := readFloppyOutput(output) data, err := readFloppyOutput(output)
if err != nil { t.Errorf("%s", err) } if err != nil {
t.Errorf("%s", err)
}
if data != "parport \n" { if data != "parport \n" {
t.Errorf("Parallel port not detected : %v", data) t.Errorf("Parallel port not detected : %v", data)
@ -279,19 +321,29 @@ func TestStepCreateVmx_Usb(t *testing.T) {
} }
// where to write output // where to write output
output,vmxData,err := createFloppyOutput("UsbOutput.") output, vmxData, err := createFloppyOutput("UsbOutput.")
if err != nil { t.Fatalf("Error creating output: %s", err) } if err != nil {
defer func() { if _,err := os.Stat(output); err == nil { os.Remove(output) } }() t.Fatalf("Error creating output: %s", err)
}
defer func() {
if _, err := os.Stat(output); err == nil {
os.Remove(output)
}
}()
config["vmx_data"] = vmxData config["vmx_data"] = vmxData
t.Logf("Preparing to write output to %s", output) t.Logf("Preparing to write output to %s", output)
// whee // whee
error := setupVMwareBuild(t, config, provision) error := setupVMwareBuild(t, config, provision)
if error != nil { t.Errorf("%s", error) } if error != nil {
t.Errorf("%s", error)
}
// check the output // check the output
data,err := readFloppyOutput(output) data, err := readFloppyOutput(output)
if err != nil { t.Errorf("%s", err) } if err != nil {
t.Errorf("%s", err)
}
if data != "USB hub found\n" { if data != "USB hub found\n" {
t.Errorf("USB support not detected : %v", data) t.Errorf("USB support not detected : %v", data)
@ -302,24 +354,34 @@ func TestStepCreateVmx_Sound(t *testing.T) {
config := map[string]string{ config := map[string]string{
"sound": `"TRUE"`, "sound": `"TRUE"`,
} }
provision := map[string]string { provision := map[string]string{
"inline": `"cat /proc/modules | egrep -o '^soundcore' > /dev/fd0"`, "inline": `"cat /proc/modules | egrep -o '^soundcore' > /dev/fd0"`,
} }
// where to write output // where to write output
output,vmxData,err := createFloppyOutput("SoundOutput.") output, vmxData, err := createFloppyOutput("SoundOutput.")
if err != nil { t.Fatalf("Error creating output: %s", err) } if err != nil {
defer func() { if _,err := os.Stat(output); err == nil { os.Remove(output) } }() t.Fatalf("Error creating output: %s", err)
}
defer func() {
if _, err := os.Stat(output); err == nil {
os.Remove(output)
}
}()
config["vmx_data"] = vmxData config["vmx_data"] = vmxData
t.Logf("Preparing to write output to %s", output) t.Logf("Preparing to write output to %s", output)
// whee // whee
error := setupVMwareBuild(t, config, provision) error := setupVMwareBuild(t, config, provision)
if error != nil { t.Errorf("Unable to read file: %s", error) } if error != nil {
t.Errorf("Unable to read file: %s", error)
}
// check the output // check the output
data,err := readFloppyOutput(output) data, err := readFloppyOutput(output)
if err != nil { t.Errorf("%s", err) } if err != nil {
t.Errorf("%s", err)
}
if data != "soundcore\n" { if data != "soundcore\n" {
t.Errorf("Soundcard not detected : %v", data) t.Errorf("Soundcard not detected : %v", data)