diff options
author | Thomas Hipp <thomashipp@gmail.com> | 2017-11-16 15:38:34 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-11-16 15:38:34 +0100 |
commit | acad5df18a9ffd03d6f6bdd2b33f4eade8e9a09d (patch) | |
tree | 286d4f3913968f3706b0f286c76b6c08a8e5c611 | |
parent | 189901b858338555651fcae7b3638a7f6d697202 (diff) | |
parent | 3a4cd93e91aad054f89491e9f91fba6cf92dbc19 (diff) | |
download | terraform-provider-libvirt-acad5df18a9ffd03d6f6bdd2b33f4eade8e9a09d.tar terraform-provider-libvirt-acad5df18a9ffd03d6f6bdd2b33f4eade8e9a09d.tar.gz |
Merge pull request #208 from MalloZup/travis-lint
Enable golint on travis, fixing all issues
29 files changed, 225 insertions, 201 deletions
diff --git a/.travis.yml b/.travis.yml index a33675bc..ab45ae97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,10 +7,12 @@ go_import_path: github.com/dmacvicar/terraform-provider-libvirt install: true before_script: - go get github.com/mattn/goveralls + - go get github.com/golang/lint/golint - sudo bash ./travis/setup-host - sudo lxc exec libvirt -- bash /code/travis/setup-guest script: - bash ./travis/gofmtcheck.sh + - golint -set_exit_status libvirt/ - sudo lxc exec libvirt -- bash /code/travis/run-tests-inside-guest - sudo lxc file pull libvirt/root/go/src/github.com/dmacvicar/terraform-provider-libvirt/profile.cov . - goveralls -coverprofile=profile.cov -service=travis-ci diff --git a/libvirt/cloudinit_def.go b/libvirt/cloudinit_def.go index 37f4afb4..fb148b75 100644 --- a/libvirt/cloudinit_def.go +++ b/libvirt/cloudinit_def.go @@ -19,10 +19,13 @@ import ( "gopkg.in/yaml.v2" ) -// names of the files expected by cloud-init +// USERDATA is the filename expected by cloud-init const USERDATA string = "user-data" + +// METADATA is the filename expected by cloud-init const METADATA string = "meta-data" +// CloudInitUserData struct type CloudInitUserData struct { SSHAuthorizedKeys []string `yaml:"ssh_authorized_keys"` } @@ -95,13 +98,13 @@ func (ci *defCloudInit) CreateAndUpload(virConn *libvirt.Connect) (string, error volumeDef.Capacity.Value = size volumeDef.Target.Format.Type = "raw" - volumeDefXml, err := xml.Marshal(volumeDef) + volumeDefXML, err := xml.Marshal(volumeDef) if err != nil { return "", fmt.Errorf("Error serializing libvirt volume: %s", err) } // create the volume - volume, err := pool.StorageVolCreateXML(string(volumeDefXml), 0) + volume, err := pool.StorageVolCreateXML(string(volumeDefXML), 0) if err != nil { return "", fmt.Errorf("Error creating libvirt volume for cloudinit device %s: %s", ci.Name, err) } diff --git a/libvirt/cloudinit_def_test.go b/libvirt/cloudinit_def_test.go index 30dfb2f3..ab01f4e7 100644 --- a/libvirt/cloudinit_def_test.go +++ b/libvirt/cloudinit_def_test.go @@ -22,12 +22,12 @@ func TestTerraformKeyOps(t *testing.T) { volKey := "volume-key" - terraformId := ci.buildTerraformKey(volKey) - if terraformId == "" { + terraformID := ci.buildTerraformKey(volKey) + if terraformID == "" { t.Error("key should not be empty") } - actualKey, _ := getCloudInitVolumeKeyFromTerraformID(terraformId) + actualKey, _ := getCloudInitVolumeKeyFromTerraformID(terraformID) if actualKey != volKey { t.Error("wrong key returned") } @@ -136,9 +136,9 @@ func TestMergeUserDataIntoEmptyUserDataRaw(t *testing.T) { } func TestMergeUserDataIntoUserDataRawGivesPrecedenceToRawData(t *testing.T) { - ud_key := "user-data-key" + udKey := "user-data-key" ud := CloudInitUserData{ - SSHAuthorizedKeys: []string{ud_key}, + SSHAuthorizedKeys: []string{udKey}, } var userDataRaw = ` @@ -152,7 +152,7 @@ ssh_authorized_keys: t.Errorf("Unexpectd error %v", err) } - if strings.Contains(res, ud_key) { + if strings.Contains(res, udKey) { t.Error("Should not have found string defined by user data") } diff --git a/libvirt/coreos_ignition_def.go b/libvirt/coreos_ignition_def.go index 084979fc..4e77b199 100644 --- a/libvirt/coreos_ignition_def.go +++ b/libvirt/coreos_ignition_def.go @@ -75,13 +75,13 @@ func (ign *defIgnition) CreateAndUpload(virConn *libvirt.Connect) (string, error volumeDef.Capacity.Value = size volumeDef.Target.Format.Type = "raw" - volumeDefXml, err := xml.Marshal(volumeDef) + volumeDefXML, err := xml.Marshal(volumeDef) if err != nil { return "", fmt.Errorf("Error serializing libvirt volume: %s", err) } // create the volume - volume, err := pool.StorageVolCreateXML(string(volumeDefXml), 0) + volume, err := pool.StorageVolCreateXML(string(volumeDefXML), 0) if err != nil { return "", fmt.Errorf("Error creating libvirt volume for Ignition %s: %s", ign.Name, err) } @@ -131,7 +131,7 @@ func (ign *defIgnition) createFile() (string, error) { file = true if _, err := os.Stat(ign.Content); err != nil { var js map[string]interface{} - if err_conf := json.Unmarshal([]byte(ign.Content), &js); err_conf != nil { + if errConf := json.Unmarshal([]byte(ign.Content), &js); errConf != nil { return "", fmt.Errorf("coreos_ignition 'content' is neither a file "+ "nor a valid json object %s", ign.Content) } diff --git a/libvirt/disk_def.go b/libvirt/disk_def.go index ed65c290..3283f03b 100644 --- a/libvirt/disk_def.go +++ b/libvirt/disk_def.go @@ -6,7 +6,7 @@ import ( "github.com/libvirt/libvirt-go-xml" ) -const OUI = "05abcd" +const oui = "05abcd" func newDefDisk() libvirtxml.DomainDisk { return libvirtxml.DomainDisk{ @@ -43,5 +43,5 @@ func randomWWN(strlen int) string { for i := 0; i < strlen; i++ { result[i] = chars[rand.Intn(len(chars))] } - return OUI + string(result) + return oui + string(result) } diff --git a/libvirt/libvirt_domain_mock_test.go b/libvirt/libvirt_domain_mock_test.go index b54feb61..151b07c9 100644 --- a/libvirt/libvirt_domain_mock_test.go +++ b/libvirt/libvirt_domain_mock_test.go @@ -2,10 +2,10 @@ package libvirt import "github.com/libvirt/libvirt-go" -type LibVirtDomainMock struct { +type DomainMock struct { QemuAgentCommandResponse string } -func (d LibVirtDomainMock) QemuAgentCommand(command string, timeout libvirt.DomainQemuAgentCommandTimeout, flags uint32) (string, error) { +func (d DomainMock) QemuAgentCommand(command string, timeout libvirt.DomainQemuAgentCommandTimeout, flags uint32) (string, error) { return d.QemuAgentCommandResponse, nil } diff --git a/libvirt/libvirt_interfaces.go b/libvirt/libvirt_interfaces.go index 77449034..5623cde2 100644 --- a/libvirt/libvirt_interfaces.go +++ b/libvirt/libvirt_interfaces.go @@ -2,12 +2,13 @@ package libvirt import "github.com/libvirt/libvirt-go" -// Interface used to expose a libvirt.Domain +// Domain Interface used to expose a libvirt.Domain // Used to allow testing -type LibVirtDomain interface { +type Domain interface { QemuAgentCommand(command string, timeout libvirt.DomainQemuAgentCommandTimeout, flags uint32) (string, error) } -type LibVirtNetwork interface { +// Network interface used to expose a libvirt.Network +type Network interface { GetXMLDesc(flags libvirt.NetworkXMLFlags) (string, error) } diff --git a/libvirt/libvirt_network_mock_test.go b/libvirt/libvirt_network_mock_test.go index a92930b0..5b856e28 100644 --- a/libvirt/libvirt_network_mock_test.go +++ b/libvirt/libvirt_network_mock_test.go @@ -2,11 +2,11 @@ package libvirt import "github.com/libvirt/libvirt-go" -type LibVirtNetworkMock struct { +type NetworkMock struct { GetXMLDescReply string GetXMLDescError error } -func (n LibVirtNetworkMock) GetXMLDesc(flags libvirt.NetworkXMLFlags) (string, error) { +func (n NetworkMock) GetXMLDesc(flags libvirt.NetworkXMLFlags) (string, error) { return n.GetXMLDescReply, n.GetXMLDescError } diff --git a/libvirt/network_def.go b/libvirt/network_def.go index dcfa7eb0..77ead849 100644 --- a/libvirt/network_def.go +++ b/libvirt/network_def.go @@ -7,7 +7,7 @@ import ( "github.com/libvirt/libvirt-go-xml" ) -// Check if the network has a DHCP server managed by libvirt +// HasDHCP checks if the network has a DHCP server managed by libvirt func HasDHCP(net libvirtxml.Network) bool { if net.Forward != nil { if net.Forward.Mode == "nat" || net.Forward.Mode == "route" || net.Forward.Mode == "" { @@ -27,13 +27,13 @@ func newDefNetworkFromXML(s string) (libvirtxml.Network, error) { return networkDef, nil } -func newDefNetworkfromLibvirt(network LibVirtNetwork) (libvirtxml.Network, error) { - networkXmlDesc, err := network.GetXMLDesc(0) +func newDefNetworkfromLibvirt(network Network) (libvirtxml.Network, error) { + networkXMLDesc, err := network.GetXMLDesc(0) if err != nil { return libvirtxml.Network{}, fmt.Errorf("Error retrieving libvirt domain XML description: %s", err) } networkDef := libvirtxml.Network{} - err = xml.Unmarshal([]byte(networkXmlDesc), &networkDef) + err = xml.Unmarshal([]byte(networkXMLDesc), &networkDef) if err != nil { return libvirtxml.Network{}, fmt.Errorf("Error reading libvirt network XML description: %s", err) } diff --git a/libvirt/network_def_test.go b/libvirt/network_def_test.go index ddb5be4b..2762f779 100644 --- a/libvirt/network_def_test.go +++ b/libvirt/network_def_test.go @@ -127,7 +127,7 @@ func TestHasDHCPForwardSet(t *testing.T) { } func TestNetworkFromLibvirtError(t *testing.T) { - net := LibVirtNetworkMock{ + net := NetworkMock{ GetXMLDescError: errors.New("boom"), } @@ -138,7 +138,7 @@ func TestNetworkFromLibvirtError(t *testing.T) { } func TestNetworkFromLibvirtWrongResponse(t *testing.T) { - net := LibVirtNetworkMock{ + net := NetworkMock{ GetXMLDescReply: "wrong xml", } @@ -149,7 +149,7 @@ func TestNetworkFromLibvirtWrongResponse(t *testing.T) { } func TestNetworkFromLibvirt(t *testing.T) { - net := LibVirtNetworkMock{ + net := NetworkMock{ GetXMLDescReply: ` <network> <name>default</name> diff --git a/libvirt/pool_sync.go b/libvirt/pool_sync.go index 8c53ac05..a50528bc 100644 --- a/libvirt/pool_sync.go +++ b/libvirt/pool_sync.go @@ -4,25 +4,25 @@ import ( "sync" ) -// LibVirtPoolSync makes possible to synchronize operations +// LVirtPoolSync makes possible to synchronize operations // against libvirt pools. // Doing pool.Refresh() operations while uploading or removing // a volume into the pool causes errors inside of libvirtd -type LibVirtPoolSync struct { +type LVirtPoolSync struct { PoolLocks map[string]*sync.Mutex internalMutex sync.Mutex } -// Allocate a new instance of LibVirtPoolSync -func NewLibVirtPoolSync() LibVirtPoolSync { - pool := LibVirtPoolSync{} +// NewLVirtPoolSync allocates a new instance of LVirtPoolSync +func NewLVirtPoolSync() LVirtPoolSync { + pool := LVirtPoolSync{} pool.PoolLocks = make(map[string]*sync.Mutex) return pool } -// Acquire a lock for the specified pool -func (ps LibVirtPoolSync) AcquireLock(pool string) { +// AcquireLock acquires a lock for the specified pool +func (ps LVirtPoolSync) AcquireLock(pool string) { ps.internalMutex.Lock() defer ps.internalMutex.Unlock() @@ -35,8 +35,8 @@ func (ps LibVirtPoolSync) AcquireLock(pool string) { lock.Lock() } -// Release the look for the specified pool -func (ps LibVirtPoolSync) ReleaseLock(pool string) { +// ReleaseLock releases the look for the specified pool +func (ps LVirtPoolSync) ReleaseLock(pool string) { ps.internalMutex.Lock() defer ps.internalMutex.Unlock() diff --git a/libvirt/pool_sync_test.go b/libvirt/pool_sync_test.go index 630ae2a4..90ad4849 100644 --- a/libvirt/pool_sync_test.go +++ b/libvirt/pool_sync_test.go @@ -5,7 +5,7 @@ import ( ) func TestAcquireLock(t *testing.T) { - ps := NewLibVirtPoolSync() + ps := NewLVirtPoolSync() ps.AcquireLock("test") @@ -17,7 +17,7 @@ func TestAcquireLock(t *testing.T) { } func TestReleaseLock(t *testing.T) { - ps := NewLibVirtPoolSync() + ps := NewLVirtPoolSync() ps.AcquireLock("test") @@ -34,7 +34,7 @@ func TestReleaseLock(t *testing.T) { } func TestReleaseNotExistingLock(t *testing.T) { - ps := NewLibVirtPoolSync() + ps := NewLVirtPoolSync() ps.ReleaseLock("test") _, found := ps.PoolLocks["test"] diff --git a/libvirt/provider.go b/libvirt/provider.go index 010ad8b4..c5f9b09f 100644 --- a/libvirt/provider.go +++ b/libvirt/provider.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) +// Provider libvirt func Provider() terraform.ResourceProvider { return &schema.Provider{ Schema: map[string]*schema.Schema{ diff --git a/libvirt/qemu_agent.go b/libvirt/qemu_agent.go index 656a1261..82e76685 100644 --- a/libvirt/qemu_agent.go +++ b/libvirt/qemu_agent.go @@ -8,17 +8,20 @@ import ( libvirt "github.com/libvirt/libvirt-go" ) +// QemuAgentInterfacesResponse type type QemuAgentInterfacesResponse struct { Interfaces []QemuAgentInterface `json:"return"` } +// QemuAgentInterface type type QemuAgentInterface struct { Name string `json:"name"` Hwaddr string `json:"hardware-address"` - IpAddresses []QemuAgentInterfaceIpAddress `json:"ip-addresses"` + IPAddresses []QemuAgentInterfaceIPAddress `json:"ip-addresses"` } -type QemuAgentInterfaceIpAddress struct { +// QemuAgentInterfaceIPAddress type +type QemuAgentInterfaceIPAddress struct { Type string `json:"ip-address-type"` Address string `json:"ip-address"` Prefix uint `json:"prefix"` @@ -29,7 +32,7 @@ type QemuAgentInterfaceIpAddress struct { // When wait4ipv4 is turned on the code will not report interfaces that don't // have a ipv4 address set. This is useful when a domain gets the ipv6 address // before the ipv4 one. -func getDomainInterfacesViaQemuAgent(domain LibVirtDomain, wait4ipv4 bool) []libvirt.DomainInterface { +func getDomainInterfacesViaQemuAgent(domain Domain, wait4ipv4 bool) []libvirt.DomainInterface { log.Print("[DEBUG] get network interfaces using qemu agent") var interfaces []libvirt.DomainInterface @@ -64,7 +67,7 @@ func getDomainInterfacesViaQemuAgent(domain LibVirtDomain, wait4ipv4 bool) []lib Hwaddr: iface.Hwaddr} ipv4Assigned := false - for _, addr := range iface.IpAddresses { + for _, addr := range iface.IPAddresses { if addr.Address == "" { // ignore interfaces without an address (eg. waiting for dhcp lease) continue diff --git a/libvirt/qemu_agent_test.go b/libvirt/qemu_agent_test.go index 1b534190..b38cd9d3 100644 --- a/libvirt/qemu_agent_test.go +++ b/libvirt/qemu_agent_test.go @@ -8,7 +8,7 @@ import ( ) func TestGetDomainInterfacesViaQemuAgentInvalidResponse(t *testing.T) { - domain := LibVirtDomainMock{} + domain := DomainMock{} interfaces := getDomainInterfacesViaQemuAgent(domain, false) @@ -25,7 +25,7 @@ func TestGetDomainInterfacesViaQemuAgentNoInterfaces(t *testing.T) { if err != nil { t.Errorf("error: %v", err) } - domain := LibVirtDomainMock{ + domain := DomainMock{ QemuAgentCommandResponse: string(data), } @@ -41,8 +41,8 @@ func TestGetDomainInterfacesViaQemuAgentIgnoreLoopbackDevice(t *testing.T) { QemuAgentInterface{ Name: "lo", Hwaddr: "ho:me", - IpAddresses: []QemuAgentInterfaceIpAddress{ - QemuAgentInterfaceIpAddress{ + IPAddresses: []QemuAgentInterfaceIPAddress{ + QemuAgentInterfaceIPAddress{ Type: "ipv4", Address: "127.0.0.1", Prefix: 1, @@ -55,7 +55,7 @@ func TestGetDomainInterfacesViaQemuAgentIgnoreLoopbackDevice(t *testing.T) { if err != nil { t.Errorf("error: %v", err) } - domain := LibVirtDomainMock{ + domain := DomainMock{ QemuAgentCommandResponse: string(data), } @@ -72,8 +72,8 @@ func TestGetDomainInterfacesViaQemuAgentIgnoreDevicesWithoutAddress(t *testing.T QemuAgentInterface{ Name: "eth1", Hwaddr: "xy:yy:zz", - IpAddresses: []QemuAgentInterfaceIpAddress{ - QemuAgentInterfaceIpAddress{ + IPAddresses: []QemuAgentInterfaceIPAddress{ + QemuAgentInterfaceIPAddress{ Type: "ipv4", Address: "", Prefix: 1, @@ -86,7 +86,7 @@ func TestGetDomainInterfacesViaQemuAgentIgnoreDevicesWithoutAddress(t *testing.T if err != nil { t.Errorf("error: %v", err) } - domain := LibVirtDomainMock{ + domain := DomainMock{ QemuAgentCommandResponse: string(data), } @@ -103,8 +103,8 @@ func TestGetDomainInterfacesViaQemuAgentUnknownIpAddressType(t *testing.T) { QemuAgentInterface{ Name: "eth2", Hwaddr: "zy:yy:zz", - IpAddresses: []QemuAgentInterfaceIpAddress{ - QemuAgentInterfaceIpAddress{ + IPAddresses: []QemuAgentInterfaceIPAddress{ + QemuAgentInterfaceIPAddress{ Type: "ipv8", Address: "i don't exist", Prefix: 1, @@ -117,7 +117,7 @@ func TestGetDomainInterfacesViaQemuAgentUnknownIpAddressType(t *testing.T) { if err != nil { t.Errorf("error: %v", err) } - domain := LibVirtDomainMock{ + domain := DomainMock{ QemuAgentCommandResponse: string(data), } @@ -139,13 +139,13 @@ func TestGetDomainInterfacesViaQemuAgent(t *testing.T) { QemuAgentInterface{ Name: device, Hwaddr: mac, - IpAddresses: []QemuAgentInterfaceIpAddress{ - QemuAgentInterfaceIpAddress{ + IPAddresses: []QemuAgentInterfaceIPAddress{ + QemuAgentInterfaceIPAddress{ Type: "ipv4", Address: ipv4Addr, Prefix: 1, }, - QemuAgentInterfaceIpAddress{ + QemuAgentInterfaceIPAddress{ Type: "ipv6", Address: ipv6Addr, Prefix: 1, @@ -158,7 +158,7 @@ func TestGetDomainInterfacesViaQemuAgent(t *testing.T) { if err != nil { t.Errorf("error: %v", err) } - domain := LibVirtDomainMock{ + domain := DomainMock{ QemuAgentCommandResponse: string(data), } diff --git a/libvirt/resource_cloud_init.go b/libvirt/resource_cloud_init.go index 6221ebc5..23639546 100644 --- a/libvirt/resource_cloud_init.go +++ b/libvirt/resource_cloud_init.go @@ -47,7 +47,7 @@ func resourceCloudInitCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] creating cloudinit") virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } cloudInit := newCloudInitDef() @@ -85,12 +85,12 @@ func resourceCloudInitCreate(d *schema.ResourceData, meta interface{}) error { func resourceCloudInitRead(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } ci, err := newCloudInitDefFromRemoteISO(virConn, d.Id()) if err != nil { - return fmt.Errorf("Error while retrieving remote ISO: %s", err) + return fmt.Errorf("error while retrieving remote ISO: %s", err) } d.Set("pool", ci.PoolName) d.Set("name", ci.Name) @@ -107,7 +107,7 @@ func resourceCloudInitRead(d *schema.ResourceData, meta interface{}) error { func resourceCloudInitDelete(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } key, err := getCloudInitVolumeKeyFromTerraformID(d.Id()) diff --git a/libvirt/resource_libvirt_coreos_ignition.go b/libvirt/resource_libvirt_coreos_ignition.go index 7762a183..01312663 100644 --- a/libvirt/resource_libvirt_coreos_ignition.go +++ b/libvirt/resource_libvirt_coreos_ignition.go @@ -36,7 +36,7 @@ func resourceIgnitionCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] creating ignition file") virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } ignition := newIgnitionDef() @@ -66,7 +66,7 @@ func resourceIgnitionCreate(d *schema.ResourceData, meta interface{}) error { func resourceIgnitionRead(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } ign, err := newIgnitionDefFromRemoteVol(virConn, d.Id()) @@ -83,7 +83,7 @@ func resourceIgnitionRead(d *schema.ResourceData, meta interface{}) error { func resourceIgnitionDelete(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } key, err := getIgnitionVolumeKeyFromTerraformID(d.Id()) diff --git a/libvirt/resource_libvirt_coreos_ignition_test.go b/libvirt/resource_libvirt_coreos_ignition_test.go index 44e2561d..027cbd3a 100644 --- a/libvirt/resource_libvirt_coreos_ignition_test.go +++ b/libvirt/resource_libvirt_coreos_ignition_test.go @@ -72,12 +72,12 @@ func testAccCheckIgnitionVolumeExists(n string, volume *libvirt.StorageVol) reso } fmt.Printf("The ID is %s", rs.Primary.ID) - realId, err := retrievedVol.GetKey() + realID, err := retrievedVol.GetKey() if err != nil { return err } - if realId != ignKey { + if realID != ignKey { return fmt.Errorf("Resource ID and volume key does not match") } diff --git a/libvirt/resource_libvirt_domain.go b/libvirt/resource_libvirt_domain.go index fadc62a6..317bfd33 100644 --- a/libvirt/resource_libvirt_domain.go +++ b/libvirt/resource_libvirt_domain.go @@ -19,12 +19,14 @@ import ( "github.com/libvirt/libvirt-go-xml" ) +// DomainMeta struct type DomainMeta struct { domain *libvirt.Domain ifaces chan libvirtxml.DomainInterface } -var PoolSync = NewLibVirtPoolSync() +// PoolSync exported pool sync +var PoolSync = NewLVirtPoolSync() func init() { spew.Config.Indent = "\t" @@ -192,7 +194,7 @@ func resourceLibvirtDomainExists(d *schema.ResourceData, meta interface{}) (bool virConn := meta.(*Client).libvirt if virConn == nil { - return false, fmt.Errorf("The libvirt connection was nil.") + return false, fmt.Errorf(LibVirtConIsNil) } domain, err := virConn.LookupDomainByUUIDString(d.Id()) @@ -212,7 +214,7 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } domainDef, err := newDomainDefForConnection(virConn) @@ -224,17 +226,16 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error } if ignition, ok := d.GetOk("coreos_ignition"); ok { - //var fw_cfg []defCmd - var fw_cfg []libvirtxml.DomainQEMUCommandlineArg + var fwCfg []libvirtxml.DomainQEMUCommandlineArg ignitionKey, err := getIgnitionVolumeKeyFromTerraformID(ignition.(string)) if err != nil { return err } - ign_str := fmt.Sprintf("name=opt/com.coreos/config,file=%s", ignitionKey) - fw_cfg = append(fw_cfg, libvirtxml.DomainQEMUCommandlineArg{"-fw_cfg"}) - fw_cfg = append(fw_cfg, libvirtxml.DomainQEMUCommandlineArg{ign_str}) + ignStr := fmt.Sprintf("name=opt/com.coreos/config,file=%s", ignitionKey) + fwCfg = append(fwCfg, libvirtxml.DomainQEMUCommandlineArg{"-fw_cfg"}) + fwCfg = append(fwCfg, libvirtxml.DomainQEMUCommandlineArg{ignStr}) QemuCmdline := &libvirtxml.DomainQEMUCommandline{ - Args: fw_cfg, + Args: fwCfg, } domainDef.QEMUCommandline = QemuCmdline } @@ -248,20 +249,20 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error domainDef.Devices.Graphics = nil } else { if graphics, ok := d.GetOk("graphics"); ok { - graphics_map := graphics.(map[string]interface{}) + graphicsMap := graphics.(map[string]interface{}) domainDef.Devices.Graphics = []libvirtxml.DomainGraphic{ libvirtxml.DomainGraphic{}, } - if graphics_type, ok := graphics_map["type"]; ok { - domainDef.Devices.Graphics[0].Type = graphics_type.(string) + if graphicsType, ok := graphicsMap["type"]; ok { + domainDef.Devices.Graphics[0].Type = graphicsType.(string) } - if autoport, ok := graphics_map["autoport"]; ok { + if autoport, ok := graphicsMap["autoport"]; ok { domainDef.Devices.Graphics[0].AutoPort = autoport.(string) } - if listen_type, ok := graphics_map["listen_type"]; ok { + if listenType, ok := graphicsMap["listen_type"]; ok { domainDef.Devices.Graphics[0].Listeners = []libvirtxml.DomainGraphicListener{ libvirtxml.DomainGraphicListener{ - Type: listen_type.(string), + Type: listenType.(string), }, } } @@ -269,10 +270,10 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error } if cpu, ok := d.GetOk("cpu"); ok { - cpu_map := cpu.(map[string]interface{}) - if cpu_mode, ok := cpu_map["mode"]; ok { + cpuMap := cpu.(map[string]interface{}) + if cpuMode, ok := cpuMap["mode"]; ok { domainDef.CPU = &libvirtxml.DomainCPU{ - Mode: cpu_mode.(string), + Mode: cpuMode.(string), } } } @@ -284,7 +285,7 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error if firmware, ok := d.GetOk("firmware"); ok { firmwareFile := firmware.(string) if _, err := os.Stat(firmwareFile); os.IsNotExist(err) { - return fmt.Errorf("Could not find firmware file '%s'.", firmwareFile) + return fmt.Errorf("could not find firmware file '%s'", firmwareFile) } domainDef.OS.Loader = &libvirtxml.DomainLoader{ Path: firmwareFile, @@ -294,17 +295,17 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error } if nvram, ok := d.GetOk("nvram"); ok { - nvram_map := nvram.(map[string]interface{}) + nvramMap := nvram.(map[string]interface{}) - nvramFile := nvram_map["file"].(string) + nvramFile := nvramMap["file"].(string) if _, err := os.Stat(nvramFile); os.IsNotExist(err) { - return fmt.Errorf("Could not find nvram file '%s'.", nvramFile) + return fmt.Errorf("could not find nvram file '%s'", nvramFile) } nvramTemplateFile := "" - if nvram_template, ok := nvram_map["template"]; ok { - nvramTemplateFile = nvram_template.(string) + if nvramTemplate, ok := nvramMap["template"]; ok { + nvramTemplateFile = nvramTemplate.(string) if _, err := os.Stat(nvramTemplateFile); os.IsNotExist(err) { - return fmt.Errorf("Could not find nvram template file '%s'.", nvramTemplateFile) + return fmt.Errorf("could not find nvram template file '%s'", nvramTemplateFile) } } domainDef.OS.NVRam = &libvirtxml.DomainNVRam{ @@ -319,8 +320,8 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error bootDeviceCount := d.Get("boot_device.#").(int) for i := 0; i < bootDeviceCount; i++ { prefix := fmt.Sprintf("boot_device.%d", i) - if boot_map, ok := d.GetOk(prefix + ".dev"); ok { - for _, dev := range boot_map.([]interface{}) { + if bootMap, ok := d.GetOk(prefix + ".dev"); ok { + for _, dev := range bootMap.([]interface{}) { bootDevice.Dev = dev.(string) bootDevices = append(bootDevices, bootDevice) } @@ -347,16 +348,16 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error Port: &consoleTargetPort, } } - if source_path, ok := d.GetOk(consolePrefix + ".source_path"); ok { + if sourcePath, ok := d.GetOk(consolePrefix + ".source_path"); ok { console.Source = &libvirtxml.DomainChardevSource{ - Path: source_path.(string), + Path: sourcePath.(string), } } - if target_type, ok := d.GetOk(consolePrefix + ".target_type"); ok { + if targetType, ok := d.GetOk(consolePrefix + ".target_type"); ok { if console.Target == nil { console.Target = &libvirtxml.DomainConsoleTarget{} } - console.Target.Type = target_type.(string) + console.Target.Type = targetType.(string) } consoles = append(consoles, console) } @@ -364,7 +365,7 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error disksCount := d.Get("disk.#").(int) var disks []libvirtxml.DomainDisk - var scsiDisk bool = false + var scsiDisk = false for i := 0; i < disksCount; i++ { disk := libvirtxml.DomainDisk{ Type: "file", @@ -682,16 +683,16 @@ func resourceLibvirtDomainCreate(d *schema.ResourceData, meta interface{}) error // if we were waiting for an IP address for this MAC, go ahead. if pending, ok := partialNetIfaces[mac]; ok { // we should have the address now - if addressesI, ok := d.GetOk(prefix + ".addresses"); !ok { + addressesI, ok := d.GetOk(prefix + ".addresses") + if !ok { return fmt.Errorf("Did not obtain the IP address for MAC=%s", mac) - } else { - for _, addressI := range addressesI.([]interface{}) { - address := addressI.(string) - log.Printf("[INFO] Finally adding IP/MAC/host=%s/%s/%s", address, mac, pending.hostname) - addHost(pending.network, address, mac, pending.hostname) - if err != nil { - return fmt.Errorf("Could not add IP/MAC/host=%s/%s/%s: %s", address, mac, pending.hostname, err) - } + } + for _, addressI := range addressesI.([]interface{}) { + address := addressI.(string) + log.Printf("[INFO] Finally adding IP/MAC/host=%s/%s/%s", address, mac, pending.hostname) + addHost(pending.network, address, mac, pending.hostname) + if err != nil { + return fmt.Errorf("Could not add IP/MAC/host=%s/%s/%s: %s", address, mac, pending.hostname, err) } } } @@ -705,7 +706,7 @@ func resourceLibvirtDomainUpdate(d *schema.ResourceData, meta interface{}) error virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } domain, err := virConn.LookupDomainByUUIDString(d.Id()) if err != nil { @@ -805,7 +806,7 @@ func resourceLibvirtDomainRead(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } domain, err := virConn.LookupDomainByUUIDString(d.Id()) @@ -1024,7 +1025,7 @@ func resourceLibvirtDomainDelete(d *schema.ResourceData, meta interface{}) error virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } log.Printf("[DEBUG] Deleting domain %s", d.Id()) diff --git a/libvirt/resource_libvirt_domain_test.go b/libvirt/resource_libvirt_domain_test.go index 9b81951a..954f1ba5 100644 --- a/libvirt/resource_libvirt_domain_test.go +++ b/libvirt/resource_libvirt_domain_test.go @@ -511,12 +511,12 @@ func testAccCheckLibvirtDomainExists(n string, domain *libvirt.Domain) resource. log.Printf("The ID is %s", rs.Primary.ID) - realId, err := retrieveDomain.GetUUIDString() + realID, err := retrieveDomain.GetUUIDString() if err != nil { return err } - if realId != rs.Primary.ID { + if realID != rs.Primary.ID { return fmt.Errorf("Libvirt domain not found") } diff --git a/libvirt/resource_libvirt_network.go b/libvirt/resource_libvirt_network.go index da201634..50bcedf8 100644 --- a/libvirt/resource_libvirt_network.go +++ b/libvirt/resource_libvirt_network.go @@ -113,7 +113,7 @@ func dnsForwarderSchema() map[string]*schema.Schema { func resourceLibvirtNetworkExists(d *schema.ResourceData, meta interface{}) (bool, error) { virConn := meta.(*Client).libvirt if virConn == nil { - return false, fmt.Errorf("The libvirt connection was nil.") + return false, fmt.Errorf(LibVirtConIsNil) } network, err := virConn.LookupNetworkByUUIDString(d.Id()) if err != nil { @@ -132,7 +132,7 @@ func resourceLibvirtNetworkExists(d *schema.ResourceData, meta interface{}) (boo func resourceLibvirtNetworkUpdate(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } network, err := virConn.LookupNetworkByUUIDString(d.Id()) if err != nil { @@ -165,7 +165,7 @@ func resourceLibvirtNetworkCreate(d *schema.ResourceData, meta interface{}) erro // see https://libvirt.org/formatnetwork.html virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } networkDef := newNetworkDef() @@ -248,12 +248,12 @@ func resourceLibvirtNetworkCreate(d *schema.ResourceData, meta interface{}) erro networkDef.IPs = ipsPtrsLst } - if dns_forward_count, ok := d.GetOk("dns_forwarder.#"); ok { + if dnsForwardCount, ok := d.GetOk("dns_forwarder.#"); ok { dns := libvirtxml.NetworkDNS{ Forwarders: []libvirtxml.NetworkDNSForwarder{}, } - for i := 0; i < dns_forward_count.(int); i++ { + for i := 0; i < dnsForwardCount.(int); i++ { forward := libvirtxml.NetworkDNSForwarder{} forwardPrefix := fmt.Sprintf("dns_forwarder.%d", i) if address, ok := d.GetOk(forwardPrefix + ".address"); ok { @@ -337,7 +337,7 @@ func resourceLibvirtNetworkCreate(d *schema.ResourceData, meta interface{}) erro func resourceLibvirtNetworkRead(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } network, err := virConn.LookupNetworkByUUIDString(d.Id()) @@ -396,7 +396,7 @@ func resourceLibvirtNetworkRead(d *schema.ResourceData, meta interface{}) error func resourceLibvirtNetworkDelete(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } log.Printf("[DEBUG] Deleting network ID %s", d.Id()) diff --git a/libvirt/resource_libvirt_volume.go b/libvirt/resource_libvirt_volume.go index 234772db..afd5b16d 100644 --- a/libvirt/resource_libvirt_volume.go +++ b/libvirt/resource_libvirt_volume.go @@ -82,7 +82,7 @@ func remoteImageSize(url string) (int, error) { func resourceLibvirtVolumeCreate(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } poolName := "default" @@ -101,7 +101,7 @@ func resourceLibvirtVolumeCreate(d *schema.ResourceData, meta interface{}) error // Refresh the pool of the volume so that libvirt knows it is // not longer in use. - WaitForSuccess("Error refreshing pool for volume", func() error { + WaitForSuccess("error refreshing pool for volume", func() error { return pool.Refresh(0) }) @@ -119,32 +119,32 @@ func resourceLibvirtVolumeCreate(d *schema.ResourceData, meta interface{}) error var ( img image - volume *libvirt.StorageVol = nil + volume *libvirt.StorageVol ) // an source image was given, this mean we can't choose size if source, ok := d.GetOk("source"); ok { // source and size conflict if _, ok := d.GetOk("size"); ok { - return fmt.Errorf("'size' can't be specified when also 'source' is given (the size will be set to the size of the source image.") + return fmt.Errorf("'size' can't be specified when also 'source' is given (the size will be set to the size of the source image") } if _, ok := d.GetOk("base_volume_id"); ok { - return fmt.Errorf("'base_volume_id' can't be specified when also 'source' is given.") + return fmt.Errorf("'base_volume_id' can't be specified when also 'source' is given") } if _, ok := d.GetOk("base_volume_name"); ok { - return fmt.Errorf("'base_volume_name' can't be specified when also 'source' is given.") + return fmt.Errorf("'base_volume_name' can't be specified when also 'source' is given") } // Check if we already have this image in the pool if len(volumeDef.Name) > 0 { if v, err := pool.LookupStorageVolByName(volumeDef.Name); err != nil { - log.Printf("Could not find image %s in pool %s", volumeDef.Name, poolName) + log.Printf("could not find image %s in pool %s", volumeDef.Name, poolName) } else { volume = v volumeDef, err = newDefVolumeFromLibvirt(volume) if err != nil { - return fmt.Errorf("could not get a volume definition from XML for %s: %s.", volumeDef.Name, err) + return fmt.Errorf("could not get a volume definition from XML for %s: %s", volumeDef.Name, err) } } } @@ -154,47 +154,47 @@ func resourceLibvirtVolumeCreate(d *schema.ResourceData, meta interface{}) error } // update the image in the description, even if the file has not changed - if size, err := img.Size(); err != nil { + size, err := img.Size() + if err != nil { return err - } else { - log.Printf("Image %s image is: %d bytes", img, size) - volumeDef.Capacity.Unit = "B" - volumeDef.Capacity.Value = size } + log.Printf("Image %s image is: %d bytes", img, size) + volumeDef.Capacity.Unit = "B" + volumeDef.Capacity.Value = size } else { _, noSize := d.GetOk("size") _, noBaseVol := d.GetOk("base_volume_id") if noSize && noBaseVol { - return fmt.Errorf("'size' needs to be specified if no 'source' or 'base_volume_id' is given.") + return fmt.Errorf("'size' needs to be specified if no 'source' or 'base_volume_id' is given") } volumeDef.Capacity.Value = uint64(d.Get("size").(int)) } - if baseVolumeId, ok := d.GetOk("base_volume_id"); ok { + if baseVolumeID, ok := d.GetOk("base_volume_id"); ok { if _, ok := d.GetOk("size"); ok { - return fmt.Errorf("'size' can't be specified when also 'base_volume_id' is given (the size will be set to the size of the backing image.") + return fmt.Errorf("'size' can't be specified when also 'base_volume_id' is given (the size will be set to the size of the backing image") } if _, ok := d.GetOk("base_volume_name"); ok { - return fmt.Errorf("'base_volume_name' can't be specified when also 'base_volume_id' is given.") + return fmt.Errorf("'base_volume_name' can't be specified when also 'base_volume_id' is given") } volume = nil - baseVolume, err := virConn.LookupStorageVolByKey(baseVolumeId.(string)) + baseVolume, err := virConn.LookupStorageVolByKey(baseVolumeID.(string)) if err != nil { - return fmt.Errorf("Can't retrieve volume %s", baseVolumeId.(string)) + return fmt.Errorf("Can't retrieve volume %s", baseVolumeID.(string)) } backingStoreDef, err := newDefBackingStoreFromLibvirt(baseVolume) if err != nil { - return fmt.Errorf("Could not retrieve backing store %s", baseVolumeId.(string)) + return fmt.Errorf("Could not retrieve backing store %s", baseVolumeID.(string)) } volumeDef.BackingStore = &backingStoreDef } if baseVolumeName, ok := d.GetOk("base_volume_name"); ok { if _, ok := d.GetOk("size"); ok { - return fmt.Errorf("'size' can't be specified when also 'base_volume_name' is given (the size will be set to the size of the backing image.") + return fmt.Errorf("'size' can't be specified when also 'base_volume_name' is given (the size will be set to the size of the backing image") } volume = nil @@ -219,13 +219,13 @@ func resourceLibvirtVolumeCreate(d *schema.ResourceData, meta interface{}) error } if volume == nil { - volumeDefXml, err := xml.Marshal(volumeDef) + volumeDefXML, err := xml.Marshal(volumeDef) if err != nil { return fmt.Errorf("Error serializing libvirt volume: %s", err) } // create the volume - v, err := pool.StorageVolCreateXML(string(volumeDefXml), 0) + v, err := pool.StorageVolCreateXML(string(volumeDefXML), 0) if err != nil { return fmt.Errorf("Error creating libvirt volume: %s", err) } @@ -262,7 +262,7 @@ func resourceLibvirtVolumeCreate(d *schema.ResourceData, meta interface{}) error func resourceLibvirtVolumeRead(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } volume, err := virConn.LookupStorageVolByKey(d.Id()) @@ -274,49 +274,49 @@ func resourceLibvirtVolumeRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[INFO] Volume %s not found, attempting to start its pool") - volId := d.Id() + volID := d.Id() volPoolName := d.Get("pool").(string) volPool, err := virConn.LookupStoragePoolByName(volPoolName) if err != nil { - return fmt.Errorf("Error retrieving pool %s for volume %s: %s", volPoolName, volId, err) + return fmt.Errorf("Error retrieving pool %s for volume %s: %s", volPoolName, volID, err) } defer volPool.Free() active, err := volPool.IsActive() if err != nil { - return fmt.Errorf("Error retrieving status of pool %s for volume %s: %s", volPoolName, volId, err) + return fmt.Errorf("error retrieving status of pool %s for volume %s: %s", volPoolName, volID, err) } if active { - return fmt.Errorf("Can't retrieve volume %s", d.Id()) + return fmt.Errorf("can't retrieve volume %s", d.Id()) } err = volPool.Create(0) if err != nil { - return fmt.Errorf("Error starting pool %s: %s", volPoolName, err) + return fmt.Errorf("error starting pool %s: %s", volPoolName, err) } // attempt a new lookup volume, err = virConn.LookupStorageVolByKey(d.Id()) if err != nil { - return fmt.Errorf("Second attempt: Can't retrieve volume %s", d.Id()) + return fmt.Errorf("second attempt: Can't retrieve volume %s", d.Id()) } } defer volume.Free() volName, err := volume.GetName() if err != nil { - return fmt.Errorf("Error retrieving volume name: %s", err) + return fmt.Errorf("error retrieving volume name: %s", err) } volPool, err := volume.LookupPoolByVolume() if err != nil { - return fmt.Errorf("Error retrieving pool for volume: %s", err) + return fmt.Errorf("error retrieving pool for volume: %s", err) } defer volPool.Free() volPoolName, err := volPool.GetName() if err != nil { - return fmt.Errorf("Error retrieving pool name: %s", err) + return fmt.Errorf("error retrieving pool name: %s", err) } d.Set("pool", volPoolName) @@ -324,7 +324,7 @@ func resourceLibvirtVolumeRead(d *schema.ResourceData, meta interface{}) error { info, err := volume.GetInfo() if err != nil { - return fmt.Errorf("Error retrieving volume name: %s", err) + return fmt.Errorf("error retrieving volume name: %s", err) } d.Set("size", info.Capacity) @@ -334,7 +334,7 @@ func resourceLibvirtVolumeRead(d *schema.ResourceData, meta interface{}) error { func resourceLibvirtVolumeDelete(d *schema.ResourceData, meta interface{}) error { virConn := meta.(*Client).libvirt if virConn == nil { - return fmt.Errorf("The libvirt connection was nil.") + return fmt.Errorf(LibVirtConIsNil) } return RemoveVolume(virConn, d.Id()) diff --git a/libvirt/resource_libvirt_volume_test.go b/libvirt/resource_libvirt_volume_test.go index 95cabadb..9f047a67 100644 --- a/libvirt/resource_libvirt_volume_test.go +++ b/libvirt/resource_libvirt_volume_test.go @@ -47,12 +47,12 @@ func testAccCheckLibvirtVolumeExists(n string, volume *libvirt.StorageVol) resou } fmt.Printf("The ID is %s", rs.Primary.ID) - realId, err := retrievedVol.GetKey() + realID, err := retrievedVol.GetKey() if err != nil { return err } - if realId != rs.Primary.ID { + if realID != rs.Primary.ID { return fmt.Errorf("Resource ID and volume key does not match") } @@ -84,7 +84,7 @@ func testAccCheckLibvirtVolumeDoesNotExists(n string, volume *libvirt.StorageVol func TestAccLibvirtVolume_Basic(t *testing.T) { var volume libvirt.StorageVol - const testAccCheckLibvirtVolumeConfig_basic = ` + const testAccCheckLibvirtVolumeConfigBasic = ` resource "libvirt_volume" "terraform-acceptance-test-1" { name = "terraform-test" size = 1073741824 @@ -96,7 +96,7 @@ func TestAccLibvirtVolume_Basic(t *testing.T) { CheckDestroy: testAccCheckLibvirtVolumeDestroy, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccCheckLibvirtVolumeConfig_basic, + Config: testAccCheckLibvirtVolumeConfigBasic, Check: resource.ComposeTestCheckFunc( testAccCheckLibvirtVolumeExists("libvirt_volume.terraform-acceptance-test-1", &volume), resource.TestCheckResourceAttr( @@ -124,12 +124,12 @@ func TestAccLibvirtVolume_DownloadFromSource(t *testing.T) { t.Fatal(err) } - const testAccCheckLibvirtVolumeConfig_source = ` + const testAccCheckLibvirtVolumeConfigSource = ` resource "libvirt_volume" "terraform-acceptance-test-2" { name = "terraform-test" source = "%s" }` - config := fmt.Sprintf(testAccCheckLibvirtVolumeConfig_source, url) + config := fmt.Sprintf(testAccCheckLibvirtVolumeConfigSource, url) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -151,7 +151,7 @@ func TestAccLibvirtVolume_DownloadFromSource(t *testing.T) { func TestAccLibvirtVolume_Format(t *testing.T) { var volume libvirt.StorageVol - const testAccCheckLibvirtVolumeConfig_format = ` + const testAccCheckLibvirtVolumeConfigFormat = ` resource "libvirt_volume" "terraform-acceptance-test-3" { name = "terraform-test" format = "raw" @@ -164,7 +164,7 @@ func TestAccLibvirtVolume_Format(t *testing.T) { CheckDestroy: testAccCheckLibvirtVolumeDestroy, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccCheckLibvirtVolumeConfig_format, + Config: testAccCheckLibvirtVolumeConfigFormat, Check: resource.ComposeTestCheckFunc( testAccCheckLibvirtVolumeExists("libvirt_volume.terraform-acceptance-test-3", &volume), resource.TestCheckResourceAttr( diff --git a/libvirt/stream.go b/libvirt/stream.go index fcfed2cf..4223466c 100644 --- a/libvirt/stream.go +++ b/libvirt/stream.go @@ -2,10 +2,12 @@ package libvirt import libvirt "github.com/libvirt/libvirt-go" +// StreamIO libvirt struct type StreamIO struct { Stream libvirt.Stream } +// NewStreamIO returns libvirt StreamIO func NewStreamIO(s libvirt.Stream) *StreamIO { return &StreamIO{Stream: s} } @@ -18,6 +20,7 @@ func (sio *StreamIO) Write(p []byte) (int, error) { return sio.Stream.Send(p) } +// Close closes the stream func (sio *StreamIO) Close() error { return sio.Stream.Finish() } diff --git a/libvirt/utils.go b/libvirt/utils.go index 0851fb8f..a82417fb 100644 --- a/libvirt/utils.go +++ b/libvirt/utils.go @@ -11,8 +11,12 @@ import ( libvirt "github.com/libvirt/libvirt-go" ) -var diskLetters []rune = []rune("abcdefghijklmnopqrstuvwxyz") +var diskLetters = []rune("abcdefghijklmnopqrstuvwxyz") +// LibVirtConIsNil is a global string error msg +const LibVirtConIsNil string = "the libvirt connection was nil" + +// DiskLetterForIndex return diskLetters for index func DiskLetterForIndex(i int) string { q := i / len(diskLetters) @@ -26,10 +30,13 @@ func DiskLetterForIndex(i int) string { return fmt.Sprintf("%s%c", DiskLetterForIndex(q-1), letter) } -var WAIT_SLEEP_INTERVAL time.Duration = 1 * time.Second -var WAIT_TIMEOUT time.Duration = 5 * time.Minute +// WaitSleepInterval time +var WaitSleepInterval = 1 * time.Second + +// WaitTimeout time +var WaitTimeout = 5 * time.Minute -// wait for success and timeout after 5 minutes. +// WaitForSuccess wait for success and timeout after 5 minutes. func WaitForSuccess(errorMessage string, f func() error) error { start := time.Now() for { @@ -39,8 +46,8 @@ func WaitForSuccess(errorMessage string, f func() error) error { } log.Printf("[DEBUG] %s. Re-trying.\n", err) - time.Sleep(WAIT_SLEEP_INTERVAL) - if time.Since(start) > WAIT_TIMEOUT { + time.Sleep(WaitSleepInterval) + if time.Since(start) > WaitTimeout { return fmt.Errorf("%s: %s", errorMessage, err) } } @@ -57,7 +64,7 @@ func xmlMarshallIndented(b interface{}) (string, error) { return buf.String(), nil } -// Remove the volume identified by `key` from libvirt +// RemoveVolume removes the volume identified by `key` from libvirt func RemoveVolume(virConn *libvirt.Connect, key string) error { volume, err := virConn.LookupStorageVolByKey(key) if err != nil { diff --git a/libvirt/utils_net.go b/libvirt/utils_net.go index efb0d725..140c4a8d 100644 --- a/libvirt/utils_net.go +++ b/libvirt/utils_net.go @@ -15,6 +15,7 @@ const ( maxIfaceNum = 100 ) +// RandomMACAddress returns a randomized MAC address func RandomMACAddress() (string, error) { buf := make([]byte, 6) _, err := rand.Read(buf) @@ -36,6 +37,7 @@ func RandomMACAddress() (string, error) { buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]), nil } +// RandomPort returns a random port func RandomPort() int { const minPort = 1024 const maxPort = 65535 @@ -44,6 +46,7 @@ func RandomPort() int { return rand.Intn(maxPort-minPort) + minPort } +// FreeNetworkInterface returns a free network interface func FreeNetworkInterface(basename string) (string, error) { for i := 0; i < maxIfaceNum; i++ { ifaceName := fmt.Sprintf("%s%d", basename, i) @@ -55,7 +58,7 @@ func FreeNetworkInterface(basename string) (string, error) { return "", fmt.Errorf("could not obtain a free network interface") } -// Calculates the first and last IP addresses in an IPNet +// NetworkRange calculates the first and last IP addresses in an IPNet func NetworkRange(network *net.IPNet) (net.IP, net.IP) { netIP := network.IP.To4() lastIP := net.IPv4(0, 0, 0, 0).To4() @@ -74,7 +77,7 @@ func NetworkRange(network *net.IPNet) (net.IP, net.IP) { type fileWebServer struct { Dir string Port int - Url string + URL string server *http.Server } @@ -87,7 +90,7 @@ func (fws *fileWebServer) Start() error { fws.Dir = dir fws.Port = RandomPort() - fws.Url = fmt.Sprintf("http://127.0.0.1:%d", fws.Port) + fws.URL = fmt.Sprintf("http://127.0.0.1:%d", fws.Port) handler := http.NewServeMux() handler.Handle("/", http.FileServer(http.Dir(dir))) @@ -113,7 +116,7 @@ func (fws *fileWebServer) AddFile(content []byte) (string, *os.File, error) { } } - return fmt.Sprintf("%s/%s", fws.Url, path.Base(tmpfile.Name())), tmpfile, nil + return fmt.Sprintf("%s/%s", fws.URL, path.Base(tmpfile.Name())), tmpfile, nil } func (fws *fileWebServer) Stop() { diff --git a/libvirt/utils_test.go b/libvirt/utils_test.go index cdcf05b9..19318216 100644 --- a/libvirt/utils_test.go +++ b/libvirt/utils_test.go @@ -36,15 +36,15 @@ func TestIPsRange(t *testing.T) { } func TestWaitForSuccessEverythingFine(t *testing.T) { - wait_sleep := WAIT_SLEEP_INTERVAL - wait_timeout := WAIT_TIMEOUT + waitSleep := WaitSleepInterval + waitTimeout := WaitTimeout defer func() { - WAIT_SLEEP_INTERVAL = wait_sleep - WAIT_TIMEOUT = wait_timeout + WaitSleepInterval = waitSleep + WaitTimeout = waitTimeout }() - WAIT_TIMEOUT = 1 * time.Second - WAIT_SLEEP_INTERVAL = 1 * time.Nanosecond + WaitTimeout = 1 * time.Second + WaitSleepInterval = 1 * time.Nanosecond err := WaitForSuccess( "boom", @@ -58,15 +58,15 @@ func TestWaitForSuccessEverythingFine(t *testing.T) { } func TestWaitForSuccessBrokenFunction(t *testing.T) { - wait_sleep := WAIT_SLEEP_INTERVAL - wait_timeout := WAIT_TIMEOUT + waitSleep := WaitSleepInterval + waitTimeout := WaitTimeout defer func() { - WAIT_SLEEP_INTERVAL = wait_sleep - WAIT_TIMEOUT = wait_timeout + WaitSleepInterval = waitSleep + WaitTimeout = waitTimeout }() - WAIT_TIMEOUT = 1 * time.Second - WAIT_SLEEP_INTERVAL = 1 * time.Nanosecond + WaitTimeout = 1 * time.Second + WaitSleepInterval = 1 * time.Nanosecond err := WaitForSuccess( "boom", diff --git a/libvirt/utils_volume.go b/libvirt/utils_volume.go index 1c97cff7..457bacb9 100644 --- a/libvirt/utils_volume.go +++ b/libvirt/utils_volume.go @@ -50,15 +50,15 @@ func (i *localImage) Import(copier func(io.Reader) error, vol libvirtxml.Storage return fmt.Errorf("Error while opening %s: %s", i.path, err) } - if fi, err := file.Stat(); err != nil { + fi, err := file.Stat() + if err != nil { return err - } else { - // we can skip the upload if the modification times are the same - if vol.Target.Timestamps != nil && vol.Target.Timestamps.Mtime != "" { - if fi.ModTime() == timeFromEpoch(vol.Target.Timestamps.Mtime) { - log.Printf("Modification time is the same: skipping image copy") - return nil - } + } + // we can skip the upload if the modification times are the same + if vol.Target.Timestamps != nil && vol.Target.Timestamps.Mtime != "" { + if fi.ModTime() == timeFromEpoch(vol.Target.Timestamps.Mtime) { + log.Printf("Modification time is the same: skipping image copy") + return nil } } diff --git a/libvirt/volume_def.go b/libvirt/volume_def.go index 6d867240..6119519e 100644 --- a/libvirt/volume_def.go +++ b/libvirt/volume_def.go @@ -38,15 +38,15 @@ func newDefVolumeFromXML(s string) (libvirtxml.StorageVolume, error) { func newDefVolumeFromLibvirt(volume *libvirt.StorageVol) (libvirtxml.StorageVolume, error) { name, err := volume.GetName() if err != nil { - return libvirtxml.StorageVolume{}, fmt.Errorf("could not get name for volume: %s.", err) + return libvirtxml.StorageVolume{}, fmt.Errorf("could not get name for volume: %s", err) } - volumeDefXml, err := volume.GetXMLDesc(0) + volumeDefXML, err := volume.GetXMLDesc(0) if err != nil { - return libvirtxml.StorageVolume{}, fmt.Errorf("could not get XML description for volume %s: %s.", name, err) + return libvirtxml.StorageVolume{}, fmt.Errorf("could not get XML description for volume %s: %s", name, err) } - volumeDef, err := newDefVolumeFromXML(volumeDefXml) + volumeDef, err := newDefVolumeFromXML(volumeDefXML) if err != nil { - return libvirtxml.StorageVolume{}, fmt.Errorf("could not get a volume definition from XML for %s: %s.", volumeDef.Name, err) + return libvirtxml.StorageVolume{}, fmt.Errorf("could not get a volume definition from XML for %s: %s", volumeDef.Name, err) } return volumeDef, nil } @@ -54,7 +54,7 @@ func newDefVolumeFromLibvirt(volume *libvirt.StorageVol) (libvirtxml.StorageVolu func newDefBackingStoreFromLibvirt(baseVolume *libvirt.StorageVol) (libvirtxml.StorageVolumeBackingStore, error) { baseVolumeDef, err := newDefVolumeFromLibvirt(baseVolume) if err != nil { - return libvirtxml.StorageVolumeBackingStore{}, fmt.Errorf("could not get volume: %s.", err) + return libvirtxml.StorageVolumeBackingStore{}, fmt.Errorf("could not get volume: %s", err) } baseVolPath, err := baseVolume.GetPath() if err != nil { |