Skip to content

Commit

Permalink
Fixing lint issues..
Browse files Browse the repository at this point in the history
  • Loading branch information
edmondshtogu committed Aug 2, 2023
1 parent c876e2f commit b53382d
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 96 deletions.
4 changes: 0 additions & 4 deletions provider/pkg/esxi/autoNamingService.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ type AutoNamingSpec struct {
MaxLength int
}

type nameSpec struct {
minLength int
maxLength int
}
type AutoNamingService struct {
rules map[string]AutoNamingSpec
}
Expand Down
6 changes: 3 additions & 3 deletions provider/pkg/esxi/connectionInfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import (

type ConnectionInfo struct {
Host string
SshPort string
SSHPort string
SslPort string
UserName string
Password string
OvfLocation string
}

func (c *ConnectionInfo) getSshConnection() string {
return fmt.Sprintf("%s:%s", c.Host, c.SshPort)
func (c *ConnectionInfo) getSSHConnection() string {
return fmt.Sprintf("%s:%s", c.Host, c.SSHPort)
}
21 changes: 13 additions & 8 deletions provider/pkg/esxi/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package esxi

import (
"fmt"
"net"
"os"
"strings"
"time"
Expand All @@ -13,6 +14,8 @@ import (

const (
failedToConnect = "failed to connect to esxi host"

attempts = 10
)

type Host struct {
Expand All @@ -23,7 +26,7 @@ type Host struct {
func NewHost(host, sshPort, sslPort, user, pass string) (*Host, error) {
connection := ConnectionInfo{
Host: host,
SshPort: sshPort,
SSHPort: sshPort,
SslPort: sslPort,
UserName: user,
Password: pass,
Expand All @@ -42,7 +45,9 @@ func NewHost(host, sshPort, sslPort, user, pass string) (*Host, error) {
}),
},
}
clientConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
clientConfig.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
}

instance := &Host{
Connection: &connection,
Expand All @@ -64,11 +69,11 @@ func (esxi *Host) validateCreds() error {
remoteCmd = "vmware --version"
_, err = esxi.Execute(remoteCmd, "Connectivity test, get vmware version")
if err != nil {
return fmt.Errorf("failed to connect to esxi host: %s", err)
return fmt.Errorf("failed to connect to esxi host: %w", err)
}

mkdir, err := esxi.Execute("mkdir -p ~", "Create home directory if missing")
logging.V(logLevel).Infof("ValidateCreds: Create home! %s %s", mkdir, err)
logging.V(logLevel).Infof("ValidateCreds: Create home! %s %s", mkdir, err.Error())

if err != nil {
return err
Expand All @@ -80,7 +85,7 @@ func (esxi *Host) validateCreds() error {
// Connect to esxi host using ssh
func (esxi *Host) connect(attempt int) (*ssh.Client, *ssh.Session, error) {
for attempt > 0 {
client, err := ssh.Dial("tcp", esxi.Connection.getSshConnection(), esxi.ClientConfig)
client, err := ssh.Dial("tcp", esxi.Connection.getSSHConnection(), esxi.ClientConfig)
if err != nil {
logging.V(logLevel).Infof("Connect: Retry attempt %d", attempt)
attempt -= 1
Expand All @@ -90,7 +95,7 @@ func (esxi *Host) connect(attempt int) (*ssh.Client, *ssh.Session, error) {
if err != nil {
closeErr := client.Close()
if closeErr != nil {
return nil, nil, fmt.Errorf("session connection error. (closing client error: %s)", closeErr)
return nil, nil, fmt.Errorf("session connection error. (closing client error: %w)", closeErr)
}
return nil, nil, fmt.Errorf("session connection error")
}
Expand Down Expand Up @@ -153,7 +158,7 @@ func (esxi *Host) WriteFile(content string, path string, shortCmdDesc string) (s
}
defer os.Remove(f.Name())

client, session, err := esxi.connect(10)
client, session, err := esxi.connect(attempts)
if err != nil {
logging.V(logLevel).Infof("Execute: Failed connecting to host! %s", err)
return failedToConnect, err
Expand All @@ -173,7 +178,7 @@ func (esxi *Host) WriteFile(content string, path string, shortCmdDesc string) (s
func (esxi *Host) CopyFile(localPath string, hostPath string, shortCmdDesc string) (string, error) {
logging.V(logLevel).Infof("CopyFile: %s", shortCmdDesc)

client, session, err := esxi.connect(10)
client, session, err := esxi.connect(attempts)
if err != nil {
logging.V(logLevel).Infof("Execute: Failed connecting to host! %s", err)
return failedToConnect, err
Expand Down
28 changes: 15 additions & 13 deletions provider/pkg/esxi/portGroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func PortGroupCreate(inputs resource.PropertyMap, esxi *Host) (string, resource.

stdout, err := esxi.Execute(command, "create port group")
if err != nil {
return "", nil, fmt.Errorf("failed to create port group: %s err:%s", stdout, err)
return "", nil, fmt.Errorf("failed to create port group: %s err:%w", stdout, err)
}

err = esxi.updatePortGroup(pg)
Expand Down Expand Up @@ -62,7 +62,7 @@ func PortGroupDelete(id string, esxi *Host) error {

stdout, err := esxi.Execute(command, "delete port group")
if err != nil {
return fmt.Errorf("failed to delete port group: %s err:%s", stdout, err)
return fmt.Errorf("failed to delete port group: %s err:%w", stdout, err)
}

return nil
Expand Down Expand Up @@ -141,7 +141,7 @@ func (esxi *Host) updatePortGroup(pg PortGroup) error {

stdout, err := esxi.Execute(command, "port group set vlan")
if err != nil {
return fmt.Errorf("failed to set port group vlan: %s err:%s", stdout, err)
return fmt.Errorf("failed to set port group vlan: %s err:%w", stdout, err)
}

command = fmt.Sprintf("esxcli network vswitch standard portgroup policy security set --use-vswitch --portgroup-name=\"%s\"", pg.Name)
Expand All @@ -158,7 +158,7 @@ func (esxi *Host) updatePortGroup(pg PortGroup) error {

stdout, err = esxi.Execute(command, "port group set security policy")
if err != nil {
return fmt.Errorf("failed to set port group security policy: %s err:%s", stdout, err)
return fmt.Errorf("failed to set port group security policy: %s err:%w", stdout, err)
}

return nil
Expand All @@ -170,19 +170,21 @@ func (esxi *Host) readPortGroup(pg PortGroup) (string, resource.PropertyMap, err

stdout, err := esxi.Execute(command, "port group list")
if stdout == "" {
return "", nil, fmt.Errorf("failed to list port group: %s err: %s", stdout, err)
return "", nil, fmt.Errorf("failed to list port group: %s err: %w", stdout, err)
}

re, _ := regexp.Compile("( {2}.* {2}) +[0-9]+ +[0-9]+$")
if len(re.FindStringSubmatch(stdout)) > 0 {
pg.VSwitch = strings.Trim(re.FindStringSubmatch(stdout)[1], " ")
re := regexp.MustCompile("( {2}.* {2}) +[0-9]+ +[0-9]+$")
matches := re.FindStringSubmatch(stdout)
if len(matches) > 0 {
pg.VSwitch = strings.Trim(matches[1], " ")
} else {
pg.VSwitch = ""
}

re, _ = regexp.Compile(" +([0-9]+)$")
if len(re.FindStringSubmatch(stdout)) > 0 {
pg.Vlan, _ = strconv.Atoi(re.FindStringSubmatch(stdout)[1])
re = regexp.MustCompile(" +([0-9]+)$")
matches = re.FindStringSubmatch(stdout)
if len(matches) > 0 {
pg.Vlan, _ = strconv.Atoi(matches[1])
} else {
pg.Vlan = 0
}
Expand All @@ -204,12 +206,12 @@ func (esxi *Host) readPortGroupSecurityPolicy(name string) (*PortGroupSecurityPo
command := fmt.Sprintf("esxcli --formatter=csv network vswitch standard portgroup policy security get -p \"%s\"", name)
stdout, err := esxi.Execute(command, "port group security policy")
if stdout == "" {
return nil, fmt.Errorf("failed to get the port group security policy: %s\n%s\n", stdout, err)
return nil, fmt.Errorf("failed to get the port group security policy: %s err: %w", stdout, err)
}

var policies []PortGroupSecurityPolicy
if err = csvutil.Unmarshal([]byte(stdout), &policies); err != nil || len(policies) != 1 {
return nil, fmt.Errorf("failed to parse the port group security policy: %s\n%s\n", stdout, err)
return nil, fmt.Errorf("failed to parse the port group security policy: %s err: %w", stdout, err)
}

return &policies[0], nil
Expand Down
2 changes: 2 additions & 0 deletions provider/pkg/esxi/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const (
vmTurnedOff = "off"
vmTurnedSuspended = "suspended"
vmSleepBetweenPowerStateChecks = 3

esxiUnknown = "Unknown"
)

type KeyValuePair struct {
Expand Down
3 changes: 2 additions & 1 deletion provider/pkg/esxi/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func structToMap(dataStruct interface{}) map[string]interface{} {
fieldType := typeOfStruct.Field(i)

// Convert the first letter of the field name to lowercase
key := string(fieldType.Name[0]+32) + fieldType.Name[1:]
const lowercaseBits = 32
key := string(fieldType.Name[0]+lowercaseBits) + fieldType.Name[1:]

switch field.Kind() {
case reflect.Struct:
Expand Down
46 changes: 20 additions & 26 deletions provider/pkg/esxi/virtualDisk.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@ import (
)

func VirtualDiskCreate(inputs resource.PropertyMap, esxi *Host) (string, resource.PropertyMap, error) {
var vd VirtualDisk
if parsed, err := parseVirtualDisk("", inputs); err == nil {
vd = parsed
} else {
return "", nil, err
}
vd := parseVirtualDisk("", inputs)
// create vd
var id, command string
var err error
Expand Down Expand Up @@ -60,12 +55,7 @@ func VirtualDiskCreate(inputs resource.PropertyMap, esxi *Host) (string, resourc
}

func VirtualDiskUpdate(id string, inputs resource.PropertyMap, esxi *Host) (string, resource.PropertyMap, error) {
var vd VirtualDisk
if parsed, err := parseVirtualDisk(id, inputs); err == nil {
vd = parsed
} else {
return "", nil, err
}
vd := parseVirtualDisk(id, inputs)

changed, err := esxi.growVirtualDisk(vd.Id, vd.Size)
if err != nil && !changed {
Expand Down Expand Up @@ -95,7 +85,7 @@ func VirtualDiskDelete(id string, esxi *Host) error {

command = fmt.Sprintf("ls -al \"/vmfs/volumes/%s/%s/\" |wc -l", vd.DiskStore, vd.Directory)

stdout, err = esxi.Execute(command, "check if storage dir is empty")
stdout, _ = esxi.Execute(command, "check if storage dir is empty")
if stdout == "3" {
{
// Delete empty dir. Ignore stdout and errors.
Expand All @@ -111,7 +101,7 @@ func VirtualDiskRead(id string, _ resource.PropertyMap, esxi *Host) (string, res
return esxi.readVirtualDisk(id)
}

func parseVirtualDisk(id string, inputs resource.PropertyMap) (VirtualDisk, error) {
func parseVirtualDisk(id string, inputs resource.PropertyMap) VirtualDisk {
vd := VirtualDisk{}
if len(id) > 0 {
vd.Id = id
Expand All @@ -132,7 +122,7 @@ func parseVirtualDisk(id string, inputs resource.PropertyMap) (VirtualDisk, erro
vd.Size = 1
}

return vd, nil
return vd
}

func (esxi *Host) readVirtualDisk(id string) (string, resource.PropertyMap, error) {
Expand Down Expand Up @@ -202,17 +192,18 @@ func (esxi *Host) getVirtualDisk(id string) (VirtualDisk, error) {
var flatSizeI64 int64
var s []string

path := strings.TrimLeft(id, "/vmfs/volumes/")
const pathParts = 3
path := strings.TrimPrefix(id, "/vmfs/volumes/")
// Extract the values from the id string
parts := strings.Split(path, "/")
if len(parts) < 3 {
if len(parts) < pathParts {
return VirtualDisk{}, fmt.Errorf("invalid virtual disk id: '%s'", id)
}

// Access the individual parts
diskStore = parts[0]
diskName = parts[len(parts)-1]
if len(parts) == 3 {
if len(parts) == pathParts {
diskDir = parts[1]
} else {
diskDir = strings.TrimLeft(path, fmt.Sprintf("%s/", diskStore))
Expand All @@ -227,8 +218,9 @@ func (esxi *Host) getVirtualDisk(id string) (VirtualDisk, error) {
}

// Get virtual disk flat size
const diskNameParts = 2
s = strings.Split(diskName, ".")
if len(s) < 2 {
if len(s) < diskNameParts {
return VirtualDisk{}, fmt.Errorf("virtual disk name %s is not valid", diskName)
}
diskNameFlat := fmt.Sprintf("%s-flat.%s", s[0], s[1])
Expand All @@ -240,7 +232,8 @@ func (esxi *Host) getVirtualDisk(id string) (VirtualDisk, error) {
return VirtualDisk{}, fmt.Errorf("failed to read virtual disk %s size, err: %s %s", id, flatSize, err)
}
flatSizeI64, _ = strconv.ParseInt(flatSize, 10, 64)
diskSize = int(flatSizeI64 / 1024 / 1024 / 1024)
const bytesSize = 1024
diskSize = int(flatSizeI64 / bytesSize / bytesSize / bytesSize)

// Determine virtual disk type (only works if Guest is powered off)
command = fmt.Sprintf("vmkfstools -t0 \"%s\" |grep -q 'VMFS Z- LVID:' && echo true", id)
Expand All @@ -252,14 +245,15 @@ func (esxi *Host) getVirtualDisk(id string) (VirtualDisk, error) {
command = fmt.Sprintf("vmkfstools -t0 \"%s\" |grep -q 'NOMP -- :' && echo true", id)
isThin, _ := esxi.Execute(command, "Get disk type. Is thin.")

if isThin == "true" {
switch {
case isThin == "true":
diskType = "thin"
} else if isZeroedThick == "true" {
case isZeroedThick == "true":
diskType = "zeroedthick"
} else if isEagerZeroedThick == "true" {
case isEagerZeroedThick == "true":
diskType = "eagerzeroedthick"
} else {
diskType = "Unknown"
default:
diskType = esxiUnknown
}

return VirtualDisk{
Expand All @@ -272,7 +266,7 @@ func (vd *VirtualDisk) toMap(keepId ...bool) map[string]interface{} {
if len(keepId) != 0 && !keepId[0] {
delete(outputs, "id")
}
if vd.DiskType == "Unknown" {
if vd.DiskType == esxiUnknown {
delete(outputs, "diskType")
}
return outputs
Expand Down
6 changes: 3 additions & 3 deletions provider/pkg/esxi/virtualMacineUtils.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ func (esxi *Host) getVirtualMachinePowerState(id string) string {
command := fmt.Sprintf("vim-cmd vmsvc/power.getstate %s", id)
stdout, _ := esxi.Execute(command, "vmsvc/power.getstate")
if strings.Contains(stdout, "Unable to find a VM corresponding") {
return "Unknown"
return esxiUnknown
}

switch {
Expand All @@ -672,7 +672,7 @@ func (esxi *Host) getVirtualMachinePowerState(id string) string {
case strings.Contains(stdout, "Suspended"):
return vmTurnedSuspended
default:
return "Unknown"
return esxiUnknown
}
}

Expand Down Expand Up @@ -727,7 +727,7 @@ func (vm *VirtualMachine) toMap(keepId ...bool) map[string]interface{} {
delete(outputs, "ovfProperties")
delete(outputs, "ovfPropertiesTimer")

if vm.BootDiskType == "Unknown" || len(vm.BootDiskType) == 0 {
if vm.BootDiskType == esxiUnknown || len(vm.BootDiskType) == 0 {
delete(outputs, "bootDiskType")
}

Expand Down
Loading

0 comments on commit b53382d

Please sign in to comment.