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"
) )
@ -216,7 +216,9 @@ func compareVersions(versionFound string, versionWanted string, product string)
// 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)
} }
@ -224,7 +226,9 @@ func ReadNetmapConfig(path string) (NetworkMap,error) {
// 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)
} }
@ -277,7 +281,9 @@ func (d *VmwareDriver) GuestAddress(state multistep.StateBag) (string,error) {
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 := ""
@ -288,7 +294,9 @@ 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
} }
@ -301,7 +309,9 @@ func (d *VmwareDriver) GuestIP(state multistep.StateBag) (string,error) {
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)
@ -312,15 +322,21 @@ func (d *VmwareDriver) GuestIP(state multistep.StateBag) (string,error) {
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)
@ -390,7 +406,9 @@ func (d *VmwareDriver) HostAddress(state multistep.StateBag) (string,error) {
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)
@ -401,10 +419,14 @@ func (d *VmwareDriver) HostAddress(state multistep.StateBag) (string,error) {
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
@ -414,19 +436,27 @@ func (d *VmwareDriver) HostAddress(state multistep.StateBag) (string,error) {
} }
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 {
@ -446,7 +476,9 @@ func (d *VmwareDriver) HostIP(state multistep.StateBag) (string,error) {
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)
@ -457,10 +489,14 @@ func (d *VmwareDriver) HostIP(state multistep.StateBag) (string,error) {
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
@ -469,14 +505,20 @@ func (d *VmwareDriver) HostIP(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
}
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
} }

View File

@ -1,12 +1,13 @@
package common package common
import ( import (
"fmt" "fmt"
"os"
"io" "io"
"strings"
"strconv"
"net" "net"
"os"
"sort" "sort"
"strconv"
"strings"
) )
type sentinelSignaller chan struct{} type sentinelSignaller chan struct{}
@ -27,9 +28,13 @@ func uncomment(eof sentinelSignaller, in <-chan byte) chan byte {
case '#': case '#':
endofline = true endofline = true
case '\n': case '\n':
if endofline { endofline = false } if endofline {
endofline = false
}
}
if !endofline {
out <- ch
} }
if !endofline { out <- ch }
} }
} }
}(in, out) }(in, out)
@ -73,14 +78,20 @@ func tokenizeDhcpConfig(eof sentinelSignaller, in chan byte) chan string {
case '\t': case '\t':
fallthrough fallthrough
case ' ': case ' ':
if len(state) == 0 { continue } if len(state) == 0 {
continue
}
out <- state out <- state
state = "" state = ""
case '{': fallthrough case '{':
case '}': fallthrough fallthrough
case '}':
fallthrough
case ';': case ';':
if len(state) > 0 { out <- state } if len(state) > 0 {
out <- state
}
out <- string(ch) out <- string(ch)
state = "" state = ""
@ -89,7 +100,9 @@ func tokenizeDhcpConfig(eof sentinelSignaller, in chan byte) chan string {
} }
} }
} }
if len(state) > 0 { out <- state } if len(state) > 0 {
out <- state
}
}(out) }(out)
return out return out
} }
@ -99,6 +112,7 @@ type tkParameter struct {
name string name string
operand []string operand []string
} }
func (e *tkParameter) String() string { func (e *tkParameter) String() string {
var values []string var values []string
for _, val := range e.operand { for _, val := range e.operand {
@ -114,6 +128,7 @@ type tkGroup struct {
groups []*tkGroup groups []*tkGroup
params []tkParameter params []tkParameter
} }
func (e *tkGroup) String() string { func (e *tkGroup) String() string {
var id []string var id []string
@ -139,9 +154,12 @@ func parseTokenParameter(in chan string) tkParameter {
continue continue
} }
switch token { switch token {
case "{": fallthrough case "{":
case "}": fallthrough fallthrough
case ";": goto leave case "}":
fallthrough
case ";":
goto leave
default: default:
result.operand = append(result.operand, token) result.operand = append(result.operand, token)
} }
@ -158,7 +176,9 @@ func parseDhcpConfig(eof sentinelSignaller, in chan string) (tkGroup,error) {
toParameter := func(tokens []string) tkParameter { toParameter := func(tokens []string) tkParameter {
out := make(chan string) out := make(chan string)
go func(out chan string) { go func(out chan string) {
for _,v := range tokens { out <- v } for _, v := range tokens {
out <- v
}
out <- ";" out <- ";"
}(out) }(out)
return parseTokenParameter(out) return parseTokenParameter(out)
@ -232,21 +252,30 @@ func tokenizeNetworkMapConfig(eof sentinelSignaller, in chan byte) chan string {
case '\t': case '\t':
fallthrough fallthrough
case ' ': case ' ':
if len(state) == 0 { continue } if len(state) == 0 {
continue
}
out <- state out <- state
state = "" state = ""
case '\n': case '\n':
if lastnewline { continue } if lastnewline {
if len(state) > 0 { out <- state } continue
}
if len(state) > 0 {
out <- state
}
out <- string(ch) out <- string(ch)
state = "" state = ""
lastnewline = true lastnewline = true
continue continue
case '.': fallthrough case '.':
fallthrough
case '=': case '=':
if len(state) > 0 { out <- state } if len(state) > 0 {
out <- state
}
out <- string(ch) out <- string(ch)
state = "" state = ""
@ -256,7 +285,9 @@ func tokenizeNetworkMapConfig(eof sentinelSignaller, in chan byte) chan string {
lastnewline = false lastnewline = false
} }
} }
if len(state) > 0 { out <- state } if len(state) > 0 {
out <- state
}
}(out) }(out)
return out return out
} }
@ -267,10 +298,14 @@ func parseNetworkMapConfig(eof sentinelSignaller, in chan string) (NetworkMap,er
addResult := func(network string, attribute string, value string) error { addResult := func(network string, attribute string, value string) error {
_, ok := unsorted[network] _, ok := unsorted[network]
if !ok { unsorted[network] = make(map[string]string) } if !ok {
unsorted[network] = make(map[string]string)
}
val, err := strconv.Unquote(value) val, err := strconv.Unquote(value)
if err != nil { return err } if err != nil {
return err
}
current := unsorted[network] current := unsorted[network]
current[attribute] = val current[attribute] = val
@ -283,20 +318,32 @@ func parseNetworkMapConfig(eof sentinelSignaller, in chan string) (NetworkMap,er
case <-eof: case <-eof:
if len(state) == 3 { if len(state) == 3 {
err := addResult(state[0], state[1], state[2]) err := addResult(state[0], state[1], state[2])
if err != nil { return nil,err } if err != nil {
return nil, err
}
} }
stillReading = false stillReading = false
case tk := <-in: case tk := <-in:
switch tk { switch tk {
case ".": case ".":
if len(state) != 1 { return nil,fmt.Errorf("Missing network index") } if len(state) != 1 {
return nil, fmt.Errorf("Missing network index")
}
case "=": case "=":
if len(state) != 2 { return nil,fmt.Errorf("Assignment to empty attribute") } if len(state) != 2 {
return nil, fmt.Errorf("Assignment to empty attribute")
}
case "\n": case "\n":
if len(state) == 0 { continue } if len(state) == 0 {
if len(state) != 3 { return nil,fmt.Errorf("Invalid attribute assignment : %v", state) } continue
}
if len(state) != 3 {
return nil, fmt.Errorf("Invalid attribute assignment : %v", state)
}
err := addResult(state[0], state[1], state[2]) err := addResult(state[0], state[1], state[2])
if err != nil { return nil,err } if err != nil {
return nil, err
}
state = make([]string, 0) state = make([]string, 0)
default: default:
state = append(state, tk) state = append(state, tk)
@ -305,7 +352,9 @@ func parseNetworkMapConfig(eof sentinelSignaller, in chan string) (NetworkMap,er
} }
result := make([]map[string]string, 0) result := make([]map[string]string, 0)
var keys []string var keys []string
for k := range unsorted { keys = append(keys, k) } for k := range unsorted {
keys = append(keys, k)
}
sort.Strings(keys) sort.Strings(keys)
for _, k := range keys { for _, k := range keys {
result = append(result, unsorted[k]) result = append(result, unsorted[k])
@ -315,17 +364,21 @@ func parseNetworkMapConfig(eof sentinelSignaller, in chan string) (NetworkMap,er
/** higher-level parsing */ /** higher-level parsing */
/// parameters /// parameters
type pParameter interface { repr() string } type pParameter interface {
repr() string
}
type pParameterInclude struct { type pParameterInclude struct {
filename string filename string
} }
func (e pParameterInclude) repr() string { return fmt.Sprintf("include-file:filename=%s", e.filename) } func (e pParameterInclude) repr() string { return fmt.Sprintf("include-file:filename=%s", e.filename) }
type pParameterOption struct { type pParameterOption struct {
name string name string
value string value string
} }
func (e pParameterOption) repr() string { return fmt.Sprintf("option:%s=%s", e.name, e.value) } func (e pParameterOption) repr() string { return fmt.Sprintf("option:%s=%s", e.name, e.value) }
// allow some-kind-of-something // allow some-kind-of-something
@ -333,14 +386,17 @@ type pParameterGrant struct {
verb string // allow,deny,ignore verb string // allow,deny,ignore
attribute string attribute string
} }
func (e pParameterGrant) repr() string { return fmt.Sprintf("grant:%s,%s", e.verb, e.attribute) } func (e pParameterGrant) repr() string { return fmt.Sprintf("grant:%s,%s", e.verb, e.attribute) }
type pParameterAddress4 []string type pParameterAddress4 []string
func (e pParameterAddress4) repr() string { func (e pParameterAddress4) repr() string {
return fmt.Sprintf("fixed-address4:%s", strings.Join(e, ",")) return fmt.Sprintf("fixed-address4:%s", strings.Join(e, ","))
} }
type pParameterAddress6 []string type pParameterAddress6 []string
func (e pParameterAddress6) repr() string { func (e pParameterAddress6) repr() string {
return fmt.Sprintf("fixed-address6:%s", strings.Join(e, ",")) return fmt.Sprintf("fixed-address6:%s", strings.Join(e, ","))
} }
@ -350,6 +406,7 @@ type pParameterHardware struct {
class string class string
address []byte address []byte
} }
func (e pParameterHardware) repr() string { func (e pParameterHardware) repr() string {
res := make([]string, 0) res := make([]string, 0)
for _, v := range e.address { for _, v := range e.address {
@ -362,12 +419,14 @@ type pParameterBoolean struct {
parameter string parameter string
truancy bool truancy bool
} }
func (e pParameterBoolean) repr() string { return fmt.Sprintf("boolean:%s=%v", e.parameter, e.truancy) } func (e pParameterBoolean) repr() string { return fmt.Sprintf("boolean:%s=%v", e.parameter, e.truancy) }
type pParameterClientMatch struct { type pParameterClientMatch struct {
name string name string
data string data string
} }
func (e pParameterClientMatch) repr() string { return fmt.Sprintf("match-client:%s=%s", e.name, e.data) } func (e pParameterClientMatch) repr() string { return fmt.Sprintf("match-client:%s=%s", e.name, e.data) }
// range 127.0.0.1 127.0.0.255 // range 127.0.0.1 127.0.0.255
@ -375,35 +434,50 @@ type pParameterRange4 struct {
min net.IP min net.IP
max net.IP max net.IP
} }
func (e pParameterRange4) repr() string { return fmt.Sprintf("range4:%s-%s",e.min.String(),e.max.String()) }
func (e pParameterRange4) repr() string {
return fmt.Sprintf("range4:%s-%s", e.min.String(), e.max.String())
}
type pParameterRange6 struct { type pParameterRange6 struct {
min net.IP min net.IP
max net.IP max net.IP
} }
func (e pParameterRange6) repr() string { return fmt.Sprintf("range6:%s-%s",e.min.String(),e.max.String()) }
func (e pParameterRange6) repr() string {
return fmt.Sprintf("range6:%s-%s", e.min.String(), e.max.String())
}
type pParameterPrefix6 struct { type pParameterPrefix6 struct {
min net.IP min net.IP
max net.IP max net.IP
bits int bits int
} }
func (e pParameterPrefix6) repr() string { return fmt.Sprintf("prefix6:/%d:%s-%s",e.bits,e.min.String(),e.max.String()) }
func (e pParameterPrefix6) repr() string {
return fmt.Sprintf("prefix6:/%d:%s-%s", e.bits, e.min.String(), e.max.String())
}
// some-kind-of-parameter 1024 // some-kind-of-parameter 1024
type pParameterOther struct { type pParameterOther struct {
parameter string parameter string
value string value string
} }
func (e pParameterOther) repr() string { return fmt.Sprintf("parameter:%s=%s", e.parameter, e.value) } func (e pParameterOther) repr() string { return fmt.Sprintf("parameter:%s=%s", e.parameter, e.value) }
type pParameterExpression struct { type pParameterExpression struct {
parameter string parameter string
expression string expression string
} }
func (e pParameterExpression) repr() string { return fmt.Sprintf("parameter-expression:%s=\"%s\"",e.parameter,e.expression) }
type pDeclarationIdentifier interface { repr() string } func (e pParameterExpression) repr() string {
return fmt.Sprintf("parameter-expression:%s=\"%s\"", e.parameter, e.expression)
}
type pDeclarationIdentifier interface {
repr() string
}
type pDeclaration struct { type pDeclaration struct {
id pDeclarationIdentifier id pDeclarationIdentifier
@ -436,27 +510,35 @@ func (e *pDeclaration) repr() string {
} }
type pDeclarationGlobal struct{} type pDeclarationGlobal struct{}
func (e pDeclarationGlobal) repr() string { return fmt.Sprintf("{global}") } func (e pDeclarationGlobal) repr() string { return fmt.Sprintf("{global}") }
type pDeclarationShared struct{ name string } type pDeclarationShared struct{ name string }
func (e pDeclarationShared) repr() string { return fmt.Sprintf("{shared-network %s}", e.name) } func (e pDeclarationShared) repr() string { return fmt.Sprintf("{shared-network %s}", e.name) }
type pDeclarationSubnet4 struct{ net.IPNet } type pDeclarationSubnet4 struct{ net.IPNet }
func (e pDeclarationSubnet4) repr() string { return fmt.Sprintf("{subnet4 %s}", e.String()) } func (e pDeclarationSubnet4) repr() string { return fmt.Sprintf("{subnet4 %s}", e.String()) }
type pDeclarationSubnet6 struct{ net.IPNet } type pDeclarationSubnet6 struct{ net.IPNet }
func (e pDeclarationSubnet6) repr() string { return fmt.Sprintf("{subnet6 %s}", e.String()) } func (e pDeclarationSubnet6) repr() string { return fmt.Sprintf("{subnet6 %s}", e.String()) }
type pDeclarationHost struct{ name string } type pDeclarationHost struct{ name string }
func (e pDeclarationHost) repr() string { return fmt.Sprintf("{host name:%s}", e.name) } func (e pDeclarationHost) repr() string { return fmt.Sprintf("{host name:%s}", e.name) }
type pDeclarationPool struct{} type pDeclarationPool struct{}
func (e pDeclarationPool) repr() string { return fmt.Sprintf("{pool}") } func (e pDeclarationPool) repr() string { return fmt.Sprintf("{pool}") }
type pDeclarationGroup struct{} type pDeclarationGroup struct{}
func (e pDeclarationGroup) repr() string { return fmt.Sprintf("{group}") } func (e pDeclarationGroup) repr() string { return fmt.Sprintf("{group}") }
type pDeclarationClass struct{ name string } type pDeclarationClass struct{ name string }
func (e pDeclarationClass) repr() string { return fmt.Sprintf("{class}") } func (e pDeclarationClass) repr() string { return fmt.Sprintf("{class}") }
/** parsers */ /** parsers */
@ -476,8 +558,10 @@ func parseParameter(val tkParameter) (pParameter,error) {
name, value := val.operand[0], val.operand[1] name, value := val.operand[0], val.operand[1]
return pParameterOption{name: name, value: value}, nil return pParameterOption{name: name, value: value}, nil
case "allow": fallthrough case "allow":
case "deny": fallthrough fallthrough
case "deny":
fallthrough
case "ignore": case "ignore":
if len(val.operand) < 1 { if len(val.operand) < 1 {
return nil, fmt.Errorf("Invalid number of parameters for pParameterGrant : %v", val.operand) return nil, fmt.Errorf("Invalid number of parameters for pParameterGrant : %v", val.operand)
@ -504,12 +588,16 @@ func parseParameter(val tkParameter) (pParameter,error) {
case "range6": case "range6":
if len(val.operand) == 1 { if len(val.operand) == 1 {
address := val.operand[0] address := val.operand[0]
if (strings.Contains(address, "/")) { if strings.Contains(address, "/") {
cidr := strings.SplitN(address, "/", 2) cidr := strings.SplitN(address, "/", 2)
if len(cidr) != 2 { return nil,fmt.Errorf("Unknown ipv6 format : %v", address) } if len(cidr) != 2 {
return nil, fmt.Errorf("Unknown ipv6 format : %v", address)
}
address := net.ParseIP(cidr[0]) address := net.ParseIP(cidr[0])
bits, err := strconv.Atoi(cidr[1]) bits, err := strconv.Atoi(cidr[1])
if err != nil { return nil,err } if err != nil {
return nil, err
}
mask := net.CIDRMask(bits, net.IPv6len*8) mask := net.CIDRMask(bits, net.IPv6len*8)
// figure out the network address // figure out the network address
@ -563,7 +651,9 @@ func parseParameter(val tkParameter) (pParameter,error) {
address := make([]byte, 0) address := make([]byte, 0)
for _, v := range octets { for _, v := range octets {
b, err := strconv.ParseInt(v, 16, 0) b, err := strconv.ParseInt(v, 16, 0)
if err != nil { return nil,err } if err != nil {
return nil, err
}
address = append(address, byte(b)) address = append(address, byte(b))
} }
return pParameterHardware{class: class, address: address}, nil return pParameterHardware{class: class, address: address}, nil
@ -627,7 +717,9 @@ func parseTokenGroup(val tkGroup) (*pDeclaration,error) {
addr := make([]byte, 4) addr := make([]byte, 4)
for i, v := range strings.SplitN(params[2], ".", 4) { for i, v := range strings.SplitN(params[2], ".", 4) {
res, err := strconv.ParseInt(v, 10, 0) res, err := strconv.ParseInt(v, 10, 0)
if err != nil { return nil,err } if err != nil {
return nil, err
}
addr[i] = byte(res) addr[i] = byte(res)
} }
oc1, oc2, oc3, oc4 := addr[0], addr[1], addr[2], addr[3] oc1, oc2, oc3, oc4 := addr[0], addr[1], addr[2], addr[3]
@ -641,7 +733,9 @@ func parseTokenGroup(val tkGroup) (*pDeclaration,error) {
if len(ip6) == 2 && strings.Contains(ip6[0], ":") { if len(ip6) == 2 && strings.Contains(ip6[0], ":") {
address := net.ParseIP(ip6[0]) address := net.ParseIP(ip6[0])
prefix, err := strconv.Atoi(ip6[1]) prefix, err := strconv.Atoi(ip6[1])
if err != nil { return nil, err } if err != nil {
return nil, err
}
return &pDeclaration{id: pDeclarationSubnet6{net.IPNet{IP: address, Mask: net.CIDRMask(prefix, net.IPv6len*8)}}}, nil return &pDeclaration{id: pDeclarationSubnet6{net.IPNet{IP: address, Mask: net.CIDRMask(prefix, net.IPv6len*8)}}}, nil
} }
} }
@ -658,16 +752,22 @@ func parseTokenGroup(val tkGroup) (*pDeclaration,error) {
func flattenDhcpConfig(root tkGroup) (*pDeclaration, error) { func flattenDhcpConfig(root tkGroup) (*pDeclaration, error) {
var result *pDeclaration var result *pDeclaration
result, err := parseTokenGroup(root) result, err := parseTokenGroup(root)
if err != nil { return nil,err } if err != nil {
return nil, err
}
for _, p := range root.params { for _, p := range root.params {
param, err := parseParameter(p) param, err := parseParameter(p)
if err != nil { return nil,err } if err != nil {
return nil, err
}
result.parameters = append(result.parameters, param) result.parameters = append(result.parameters, param)
} }
for _, p := range root.groups { for _, p := range root.groups {
group, err := flattenDhcpConfig(*p) group, err := flattenDhcpConfig(*p)
if err != nil { return nil,err } if err != nil {
return nil, err
}
group.parent = result group.parent = result
result.declarations = append(result.declarations, *group) result.declarations = append(result.declarations, *group)
} }
@ -676,11 +776,13 @@ func flattenDhcpConfig(root tkGroup) (*pDeclaration,error) {
/** reduce the tree into the things that we care about */ /** reduce the tree into the things that we care about */
type grant uint type grant uint
const ( const (
ALLOW grant = iota ALLOW grant = iota
IGNORE grant = iota IGNORE grant = iota
DENY grant = iota DENY grant = iota
) )
type configDeclaration struct { type configDeclaration struct {
id []pDeclarationIdentifier id []pDeclarationIdentifier
composites []pDeclaration composites []pDeclaration
@ -749,24 +851,40 @@ func (e *configDeclaration) repr() string {
var res []string var res []string
res = make([]string, 0) res = make([]string, 0)
for _,v := range e.id { res = append(res, v.repr()) } for _, v := range e.id {
res = append(res, v.repr())
}
result = append(result, strings.Join(res, ",")) result = append(result, strings.Join(res, ","))
if len(e.address) > 0 { if len(e.address) > 0 {
res = make([]string, 0) res = make([]string, 0)
for _,v := range e.address { res = append(res, v.repr()) } for _, v := range e.address {
res = append(res, v.repr())
}
result = append(result, fmt.Sprintf("address : %v", strings.Join(res, ","))) result = append(result, fmt.Sprintf("address : %v", strings.Join(res, ",")))
} }
if len(e.options) > 0 { result = append(result, fmt.Sprintf("options : %v", e.options)) } if len(e.options) > 0 {
if len(e.grants) > 0 { result = append(result, fmt.Sprintf("grants : %v", e.grants)) } result = append(result, fmt.Sprintf("options : %v", e.options))
if len(e.attributes) > 0 { result = append(result, fmt.Sprintf("attributes : %v", e.attributes)) } }
if len(e.parameters) > 0 { result = append(result, fmt.Sprintf("parameters : %v", e.parameters)) } if len(e.grants) > 0 {
if len(e.expressions) > 0 { result = append(result, fmt.Sprintf("parameter-expressions : %v", e.expressions)) } result = append(result, fmt.Sprintf("grants : %v", e.grants))
}
if len(e.attributes) > 0 {
result = append(result, fmt.Sprintf("attributes : %v", e.attributes))
}
if len(e.parameters) > 0 {
result = append(result, fmt.Sprintf("parameters : %v", e.parameters))
}
if len(e.expressions) > 0 {
result = append(result, fmt.Sprintf("parameter-expressions : %v", e.expressions))
}
if len(e.hostid) > 0 { if len(e.hostid) > 0 {
res = make([]string, 0) res = make([]string, 0)
for _,v := range e.hostid { res = append(res, v.repr()) } for _, v := range e.hostid {
res = append(res, v.repr())
}
result = append(result, fmt.Sprintf("hostid : %v", strings.Join(res, " "))) result = append(result, fmt.Sprintf("hostid : %v", strings.Join(res, " ")))
} }
return strings.Join(result, "\n") + "\n" return strings.Join(result, "\n") + "\n"
@ -788,9 +906,13 @@ func (e *configDeclaration) IP4() (net.IP,error) {
return nil, fmt.Errorf("No IP4 addresses found") return nil, fmt.Errorf("No IP4 addresses found")
} }
if res := net.ParseIP(result[0]); res != nil { return res,nil } if res := net.ParseIP(result[0]); res != nil {
return res, nil
}
res, err := net.ResolveIPAddr("ip4", result[0]) res, err := net.ResolveIPAddr("ip4", result[0])
if err != nil { return nil,err } if err != nil {
return nil, err
}
return res.IP, nil return res.IP, nil
} }
func (e *configDeclaration) IP6() (net.IP, error) { func (e *configDeclaration) IP6() (net.IP, error) {
@ -809,9 +931,13 @@ func (e *configDeclaration) IP6() (net.IP,error) {
return nil, fmt.Errorf("No IP6 addresses found") return nil, fmt.Errorf("No IP6 addresses found")
} }
if res := net.ParseIP(result[0]); res != nil { return res,nil } if res := net.ParseIP(result[0]); res != nil {
return res, nil
}
res, err := net.ResolveIPAddr("ip6", result[0]) res, err := net.ResolveIPAddr("ip6", result[0])
if err != nil { return nil,err } if err != nil {
return nil, err
}
return res.IP, nil return res.IP, nil
} }
func (e *configDeclaration) Hardware() (net.HardwareAddr, error) { func (e *configDeclaration) Hardware() (net.HardwareAddr, error) {
@ -834,17 +960,22 @@ func (e *configDeclaration) Hardware() (net.HardwareAddr,error) {
/*** Dhcp Configuration */ /*** Dhcp Configuration */
type DhcpConfiguration []configDeclaration type DhcpConfiguration []configDeclaration
func ReadDhcpConfiguration(fd *os.File) (DhcpConfiguration, error) { func ReadDhcpConfiguration(fd *os.File) (DhcpConfiguration, error) {
fromfile, eof := consumeFile(fd) fromfile, eof := consumeFile(fd)
uncommented := uncomment(eof, fromfile) uncommented := uncomment(eof, fromfile)
tokenized := tokenizeDhcpConfig(eof, uncommented) tokenized := tokenizeDhcpConfig(eof, uncommented)
parsetree, err := parseDhcpConfig(eof, tokenized) parsetree, err := parseDhcpConfig(eof, tokenized)
if err != nil { return nil,err } if err != nil {
return nil, err
}
global, err := flattenDhcpConfig(parsetree) global, err := flattenDhcpConfig(parsetree)
if err != nil { return nil,err } if err != nil {
return nil, err
}
var walkDeclarations func(root pDeclaration, out chan*configDeclaration); var walkDeclarations func(root pDeclaration, out chan *configDeclaration)
walkDeclarations = func(root pDeclaration, out chan *configDeclaration) { walkDeclarations = func(root pDeclaration, out chan *configDeclaration) {
res := createDeclaration(root) res := createDeclaration(root)
out <- &res out <- &res
@ -921,6 +1052,7 @@ func (e *DhcpConfiguration) HostByName(host string) (configDeclaration,error) {
/*** Network Map */ /*** Network Map */
type NetworkMap []map[string]string type NetworkMap []map[string]string
func ReadNetworkMap(fd *os.File) (NetworkMap, error) { func ReadNetworkMap(fd *os.File) (NetworkMap, error) {
fromfile, eof := consumeFile(fd) fromfile, eof := consumeFile(fd)
@ -928,7 +1060,9 @@ func ReadNetworkMap(fd *os.File) (NetworkMap,error) {
tokenized := tokenizeNetworkMapConfig(eof, uncommented) tokenized := tokenizeNetworkMapConfig(eof, uncommented)
result, err := parseNetworkMapConfig(eof, tokenized) result, err := parseNetworkMapConfig(eof, tokenized)
if err != nil { return nil,err } if err != nil {
return nil, err
}
return result, nil return result, nil
} }
@ -965,7 +1099,9 @@ func consumeFile(fd *os.File) (chan byte,sentinelSignaller) {
b := make([]byte, 1) b := make([]byte, 1)
for { for {
_, err := fd.Read(b) _, err := fd.Read(b)
if err == io.EOF { break } if err == io.EOF {
break
}
fromfile <- b[0] fromfile <- b[0]
} }
close(eof) close(eof)

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"
@ -243,11 +244,13 @@ func unformat_parallel(config string) (*parallelUnion,error) {
} }
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)
} }
@ -257,9 +260,12 @@ func unformat_parallel(config string) (*parallelUnion,error) {
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)
} }

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{
@ -57,7 +57,9 @@ func tmpnam(prefix string) string {
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{
@ -75,11 +77,17 @@ func createFloppyOutput(prefix string) (string,string,error) {
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)
}
if len(data) == 0 {
return "", nil
}
return string(data[:bytes.IndexByte(data, 0)]), nil return string(data[:bytes.IndexByte(data, 0)]), nil
} }
@ -88,8 +96,12 @@ 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{}
@ -99,8 +111,12 @@ func setupVMwareBuild(t *testing.T, builderConfig map[string]string, provisioner
// 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{}
@ -138,11 +154,15 @@ 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 {
@ -186,7 +206,9 @@ 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 {
@ -217,18 +239,28 @@ 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)
@ -252,18 +284,28 @@ 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)
@ -280,18 +322,28 @@ 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)
@ -308,18 +360,28 @@ func TestStepCreateVmx_Sound(t *testing.T) {
// 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)