vsphere

package
v0.0.0-...-492d7f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2018 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RETRY_COUNT                = 20
	GRAY_STATUS_CHECK_TIMEOUT  = 1 * time.Minute
	GREEN_STATUS_CHECK_TIMEOUT = 10 * time.Minute
	IPWAIT_TIMEOUT             = 1 * time.Hour
)
View Source
const (
	GUEST_HEART_BEAT_STATUS = "guestHeartbeatStatus"
	GREEN_HEART_BEAT        = 1 << iota
	YELLOW_HEART_BEAT
	GRAY_HEART_BEAT
	RED_HEART_BEAT
)

* The guest heartbeat. The heartbeat status is classified as: * gray - VMware Tools are not installed or not running. * red - No heartbeat. Guest operating system may have stopped responding. * yellow - Intermittent heartbeat. May be due to guest load. * green - Guest operating system is responding normally.

View Source
const (
	SKIPTEMPLATE_ERROR = iota
	SKIPTEMPLATE_OVERWRITE
	SKIPTEMPLATE_USE

	// Custom field name and value used to tag visor images
	VISOR_FIELD = "template_type"
	VISOR_VALUE = "visor"
	MO_TYPE_VM  = "VirtualMachine"
	UPLINK_TAG  = "SYSTEM/DVS.UPLINKPG"

	// Constants for supproted values for Flavor:Name
	FlavorSmall   = "small"
	FlavorMedium  = "medium"
	FlavorLarge   = "large"
	FlavorXLarge  = "xlarge"
	Flavor2XLarge = "2xlarge"
	Flavor4XLarge = "4xlarge"
	Flavor8XLarge = "8xlarge"
	FlavorCustom  = "custom"
)

constants to compare with if the template already exists SKIPTEMPLATE_ERROR : Errors out SKIPTEMPLATE_OVERWRITE : Overwrites the template and provision the vm SKIPTEMPLATE_USE : Use the existing template and provision the vm

View Source
const (
	// DestinationTypeHost represents an ESXi host in the vSphere inventory.
	DestinationTypeHost = "host"
	// DestinationTypeCluster represents a cluster in the vSphere inventory.
	DestinationTypeCluster = "cluster"
	// DestinationTypeResourcePool represents a resource pool in the vSphere inventory.
	DestinationTypeResourcePool = "resource_pool"
)
View Source
const (
	RESOURCE_POOL_DEPTH = 8
)
View Source
const STATICIP_CUSTOM_SPEC_NAME = "static-ip-libretto"
View Source
const XML_STATIC_IP_SPEC = `` /* 1722-byte string literal not displayed */

Variables

View Source
var (
	// ErrorVMExists is returned when the VM being provisioned already exists.
	ErrorVMExists = errors.New("VM already exists")
	//ErrorDestinationNotSupported is returned when the destination is not supported for provisioning.
	ErrorDestinationNotSupported = errors.New("destination is not supported by this provisioner")
	// ErrorVMPowerStateChanging is returned when the power state of the VM is resetting or shuttingdown
	// The VM can't be started in this state
	ErrorVMPowerStateChanging = errors.New("the power state of the vm is changing, try again later")
)
View Source
var Exists = func(vm *VM, searchFilter VMSearchFilter) (bool, error) {
	_, err := findVM(vm, searchFilter)
	if err != nil {
		if _, ok := err.(ErrorObjectNotFound); ok {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

Exists checks if the VM already exists.

View Source
var NewLease = func(ctx context.Context, lease *object.HttpNfcLease) Lease {
	return VMwareLease{
		Ctx:   ctx,
		Lease: lease,
	}
}

NewLease creates a VMwareLease.

View Source
var NewProgressReader = func(r io.Reader, t int64, l Lease) ProgressReader {
	return ReadProgress{
		Reader:     r,
		TotalBytes: t,
		Lease:      l,
		ch:         make(chan int64, 1),
		wg:         &sync.WaitGroup{},
	}
}

NewProgressReader returns a functional instance of ReadProgress.

View Source
var SetupSession = func(vm *VM) error {
	uri := getURI(vm.Host)
	u, err := url.Parse(uri)
	if err != nil || u.String() == "" {
		return NewErrorParsingURL(uri, err)
	}
	u.User = url.UserPassword(vm.Username, vm.Password)
	vm.uri = u
	vm.ctx, vm.cancel = context.WithCancel(context.Background())
	client, err := newClient(vm)
	if err != nil {
		return NewErrorClientFailed(err)
	}

	vm.client = client
	vm.finder = newFinder(vm.client.Client)
	vm.collector = newCollector(vm.client.Client)
	return nil
}

SetupSession is used to setup the session.

Functions

func ConvertToTemplate

func ConvertToTemplate(vm *VM) error

ConvertToTemplate : converts vm to vm template

func CreateDisk

CreateDisk creates a new VirtualDisk device which can be added to a VM.

func CreateTemplate

func CreateTemplate(vm *VM) error

CreateTemplate : uploads a template to vcenter server if doesn't exist

func DeleteTemplate

func DeleteTemplate(vm *VM) error

DeleteTemplate deletes the vm-template, created during vm provisioning

func GetClusterNetworkList

func GetClusterNetworkList(vm *VM, filter map[string][]string) ([]map[string]string, error)

GetClusterNetworkList : returns a list of network in given cluster/host available-filters (map-keys): "hosts", "clusters".

func GetDatacenter

func GetDatacenter(vm *VM) (*mo.Datacenter, error)

GetDatacenter retrieves the datacenter that the provisioner was configured against.

func GetDatacenterList

func GetDatacenterList(vm *VM) ([]map[string]string, error)

GetDatacenterList : return the list of datacenters in vcenter server

func GetDcNetworkList

func GetDcNetworkList(vm *VM, filter map[string][]string) ([]map[string]string, error)

GetDcNetworkList : returns a list of network in given datacenter available-filters (map-keys): "hosts", "clusters".

func GetNetworkInHost

func GetNetworkInHost(vm *VM) ([]map[string]string, error)

GetNetworkInHost : Returns the networks in a host in a cluster

func GetResourcePoolList

func GetResourcePoolList(vm *VM) ([]map[string]interface{}, error)

GetResourcePoolList : GetResourcePoolList returns the resource_pool_list in the datacenter

func GetVmList

func GetVmList(vm *VM, markedTemplate bool, markedVisor bool) (
	[]map[string]interface{}, error)

GetVmList : Returns the VMs/templates/visor_templates info in a dc/cluster/host

func IsClusterDrsEnabled

func IsClusterDrsEnabled(vm *VM) (bool, error)

IsClusterDrsEnabled: returns true if the cluster is drs enabled

func StringInSlice

func StringInSlice(str string, list []string) bool

Types

type ClusterComputeResource

type ClusterComputeResource struct {
	Name           string       `json:"name"`
	NumCpuCores    int16        `json:"num_cpu_cores"`
	NumCpuThreads  int16        `json:"num_cpu_threads"`
	TotalCpu       int32        `json:"total_cpu"`
	FreeCpu        int32        `json:"free_cpu"`
	TotalMemory    int64        `json:"total_memory"`
	FreeMemory     int64        `json:"free_memory"`
	TotalStorage   int64        `json:"total_storage"`
	FreeStorage    int64        `json:"free_storage"`
	NoOfHosts      int          `json:"number_hosts"`
	NoOfDatastores int          `json:"number_datastores"`
	NoOfNetworks   int          `json:"number_networks"`
	Hosts          []HostSystem `json:"hosts"`
	DrsEnabled     bool         `json:"drs_enabled"`
}

func GetDcClusterList

func GetDcClusterList(vm *VM) ([]ClusterComputeResource, error)

GetDcClusterList : GetDcClusterList returns the clusters in the datacenter

type Datastore

type Datastore struct {
	Name               string `json:"name"`
	Type               string `json:"type"`
	Shared             bool   `json:"shared"`
	Url                string `json:"url"`
	VirtualCapacity    int64  `json:"virtual_capacity"`
	Capacity           int64  `json:"capacity"`
	FreeSpace          int64  `json:"free_space"`
	Ssd                bool   `json:"ssd"`
	Local              bool   `json:"local"`
	ScsiDiskType       string `json:"scsi_disk_type"`
	MultipleHostAccess bool   `json:"multiple_host_access"`
	Accessible         bool   `json:"accessible"`
}

func GetDatastores

func GetDatastores(vm *VM) ([]Datastore, error)

GetDatastores : Returns the datastores in a host/cluster

type Destination

type Destination struct {
	// Represents the name of the destination as described in the API
	DestinationName string
	// Only the "host" type is supported for now. The VI SDK supports host, cluster
	// and resource pool.
	DestinationType string
	// HostSystem specifies the name of the host to run the VM on. DestinationType ESXi
	// will have one host system. A cluster will have more than one,
	HostSystem string
	// MorefID of managed object [Currently only use with resource pool]
	MOID string `json:"MOID"`
}

Destination represents a destination on which to provision a Virtual Machine

type Disk

type Disk struct {
	Size         float32 `json:"size,omitempty"`
	Controller   string  `json:"controller,omitempty"`
	Provisioning string  `json:"provisioning,omitempty"`
	Datastore    string  `json:"datastore,omitempty"`
	DiskFile     string  `json:"disk_file,omitempty"`
}

Disk represents a vSphere Disk to attach to the VM

type ErrorBadResponse

type ErrorBadResponse struct {
	// contains filtered or unexported fields
}

ErrorBadResponse is returned when an HTTP request gets a bad response

func NewErrorBadResponse

func NewErrorBadResponse(r *http.Response) ErrorBadResponse

NewErrorBadResponse returns an ErrorBadResponse error.

func (ErrorBadResponse) Error

func (e ErrorBadResponse) Error() string

type ErrorClientFailed

type ErrorClientFailed struct {
	// contains filtered or unexported fields
}

ErrorClientFailed is returned when a client cannot be created using the given creds

func NewErrorClientFailed

func NewErrorClientFailed(e error) ErrorClientFailed

NewErrorClientFailed returns an ErrorClientFailed error.

func (ErrorClientFailed) Error

func (e ErrorClientFailed) Error() string

type ErrorInvalidHost

type ErrorInvalidHost struct {
	// contains filtered or unexported fields
}

ErrorInvalidHost is returned when the host does not have a datastore or network selected by the user

func NewErrorInvalidHost

func NewErrorInvalidHost(h string, d string, n []Network) ErrorInvalidHost

NewErrorInvalidHost returns an ErrorInvalidHost error.

func (ErrorInvalidHost) Error

func (e ErrorInvalidHost) Error() string

type ErrorObjectNotFound

type ErrorObjectNotFound struct {
	// contains filtered or unexported fields
}

ErrorObjectNotFound is returned when the object being searched for is not found.

func NewErrorObjectNotFound

func NewErrorObjectNotFound(e error, o string) ErrorObjectNotFound

NewErrorObjectNotFound returns an ErrorObjectNotFound error.

func (ErrorObjectNotFound) Error

func (e ErrorObjectNotFound) Error() string

type ErrorParsingURL

type ErrorParsingURL struct {
	// contains filtered or unexported fields
}

ErrorParsingURL is returned when the sdk url passed to the vSphere provider is not valid

func NewErrorParsingURL

func NewErrorParsingURL(u string, e error) ErrorParsingURL

NewErrorParsingURL returns an ErrorParsingURL error.

func (ErrorParsingURL) Error

func (e ErrorParsingURL) Error() string

type ErrorPropertyRetrieval

type ErrorPropertyRetrieval struct {
	// contains filtered or unexported fields
}

ErrorPropertyRetrieval is returned when the object being searched for is not found.

func NewErrorPropertyRetrieval

func NewErrorPropertyRetrieval(m types.ManagedObjectReference, p []string, e error) ErrorPropertyRetrieval

NewErrorPropertyRetrieval returns an ErrorPropertyRetrieval error.

func (ErrorPropertyRetrieval) Error

func (e ErrorPropertyRetrieval) Error() string

type Flavor

type Flavor struct {
	// Flavor name. Supported values are defined as
	// constants [FlavorLarge, FlavorSmall, FlavorMedium, FlavorCustom]
	Name string
	// Represents the number of CPUs
	NumCPUs int32 `json:"cpu"`
	// Represents the size of main memory in MB
	MemoryMB int64 `json:"memory"`
}

type HostSystem

type HostSystem struct {
	Name            string      `json:"name"`
	CpuModel        string      `json:"cpu_model"`
	NumCpuPkgs      int16       `json:"num_cpu_pkgs"`
	NumCpuCores     int16       `json:"num_cpu_cores"`
	TotalCpu        int32       `json:"total_cpu"`
	FreeCpu         int32       `json:"free_cpu"`
	TotalMemory     int64       `json:"total_memory"`
	FreeMemory      int64       `json:"free_memory"`
	TotalStorage    int64       `json:"total_storage"`
	FreeStorage     int64       `json:"free_storage"`
	VirtualCapacity int64       `json:"virtual_capacity"`
	Datastores      []Datastore `json:"datastores"`
}

func GetHostList

func GetHostList(vm *VM) ([]HostSystem, error)

GetHostList : returns the hosts in a cluster in vcenter server

type Lease

type Lease interface {
	HTTPNfcLeaseProgress(int32)
	Wait() (*types.HttpNfcLeaseInfo, error)
	Complete() error
}

Lease represents a type that wraps around a HTTPNfcLease

type Network

type Network struct {
	Name        string
	Description string
	Operation   string
	DeviceKey   *int32 `json:"device_key"`
}

type ProgressReader

type ProgressReader interface {
	StartProgress()
	Wait()
	Read(p []byte) (n int, err error)
}

ProgressReader is an interface for interacting with the vSphere SDK. It provides a `Start` method to start a monitoring go-routine which monitors the progress of the upload as well as a `Wait` method to wait until the upload is complete.

type ReadProgress

type ReadProgress struct {
	Reader     io.Reader
	TotalBytes int64
	Lease      Lease
	// contains filtered or unexported fields
}

ReadProgress wraps a io.Reader and submits progress reports on an embedded channel

func (ReadProgress) Read

func (r ReadProgress) Read(p []byte) (n int, err error)

Read implements the Reader interface.

func (ReadProgress) StartProgress

func (r ReadProgress) StartProgress()

StartProgress starts a goroutine that updates local progress on the lease as well as pass it down to the underlying lease.

func (ReadProgress) Wait

func (r ReadProgress) Wait()

Wait waits for the underlying waitgroup to be complete.

type Template

type Template struct {
	Name         string `json:"name"`
	InstanceUuid string `json:"instance_uuid"`
}

type VM

type VM struct {
	// Host represents the vSphere host to use for creating this VM.
	Host string
	// Destination represents the destination on which to clone this VM.
	Destination Destination
	// Username represents the username to use for connecting to the sdk.
	Username string
	// Password represents the password to use for connecting to the sdk.
	Password string
	// Insecure allows connecting without cert validation when set to true.
	Insecure bool
	// Datacenter configures the datacenter onto which to import the VM.
	Datacenter string
	//Flavor for the number of CPUs and size of main memory
	Flavor Flavor
	// OvfPath represents the location of the OVF file on disk.
	OvfPath string
	// OvaPathUrl represents the location of local/remote ova file
	// If OvaPathUrl is given then OvaPathUrl will be used, if not then OvfPath will be used
	// If Both are given preference will be given to OvaPathUrl.
	OvaPathUrl string
	// Networks defines a slice of networks to be attached to the VM
	// They must be available on the host or deploy will fail.
	Networks []Network
	// Name is the name to use for the VM on vSphere and internally.
	Name string
	// InstanceUuids is the list of instance uuids for the VMs on vcenter server
	InstanceUuids []string
	// Template is the name to use for the VM's template
	Template Template
	// Datastores is a slice of permissible datastores. One is picked out of these.
	Datastores []string
	// UseLocalTemplates is a flag to indicate whether a template should be uploaded on all
	// the datastores that were passed in.
	UseLocalTemplates bool
	// SkipExisting when set to '2' lets Provision succeed even if the VM already exists.
	SkipExisting *int
	// Credentials are the credentials to use when connecting to the VM over SSH
	Credentials ssh.Credentials
	// FixedDisks is a slice of existing disks which user wants to either expand/delete from VM
	FixedDisks []Disk
	// Disks is a slice of extra disks to attach to the VM
	Disks []Disk
	// QuestionResponses is a map of regular expressions to match question text
	// to responses when a VM encounters a questions which would otherwise
	// prevent normal operation. The response strings should be the string value
	// of the intended response index.
	QuestionResponses map[string]string
	// UseLinkedClones is a flag to indicate whether VMs cloned from templates should be
	// linked clones.
	UseLinkedClones bool
	// Skip waiting for IP to be assigned to VM in create/start actions
	SkipIPWait bool `json:"skip_ip_wait"`
	// NestedHV is a flag to enable nested hardware-assisted virtualization
	NestedHV bool `json:"nested_hv"`

	NetworkSetting lvm.NetworkSetting
	// contains filtered or unexported fields
}

VM represents a vSphere VM.

func (*VM) AddDisk

func (vm *VM) AddDisk() error

AddDisk: adds given list of disks to the vm

func (*VM) Destroy

func (vm *VM) Destroy() (err error)

Destroy deletes this VM from vSphere.

func (*VM) GetIPs

func (vm *VM) GetIPs() ([]net.IP, error)

GetIPs returns the IPs of this VM. Returns all the IPs known to the API for the different network cards for this VM. Includes IPV4 and IPV6 addresses.

func (*VM) GetIPsAndIds

func (vm *VM) GetIPsAndIds() (VMInfo, error)

GetIPsAndIds returns the IPs, reference Id and instance uuid of this VM. Returns all the IPs known to the API for the different network cards for this VM. Includes IPV4 and IPV6 addresses.

func (*VM) GetName

func (vm *VM) GetName() string

GetName returns the name of this VM.

func (*VM) GetSSH

func (vm *VM) GetSSH(options ssh.Options) (ssh.Client, error)

GetSSH returns an ssh client configured for this VM.

func (*VM) GetState

func (vm *VM) GetState() (state string, err error)

GetState returns the power state of this VM.

func (*VM) GetVMInfo

func (vm *VM) GetVMInfo() (VMInfo, error)

GetVMInfo returns information of this VM.

func (*VM) Halt

func (vm *VM) Halt() (err error)

Halt halts this VM.

func (*VM) Provision

func (vm *VM) Provision() (err error)

Provision provisions this VM.

func (*VM) Reconfigure

func (vm *VM) Reconfigure() error

Reconfigure: reconfigures vm CPU, memory, network

func (*VM) RemoveDisk

func (vm *VM) RemoveDisk() error

RemoveDisk: removes given list of disks attached to the virtualmachine 'vm' disk.DiskFile is the name of the vmdk file for the disk

func (*VM) Reset

func (vm *VM) Reset() (err error)

Reset restarts this VM.

func (*VM) Restart

func (vm *VM) Restart() (err error)

Restart Initiates guest reboot of this VM.

func (*VM) Resume

func (vm *VM) Resume() (err error)

Resume resumes this VM from a suspended or powered off state.

func (*VM) ShutDown

func (vm *VM) ShutDown() (err error)

ShutDown Initiates guest shut down of this VM.

func (*VM) Start

func (vm *VM) Start() (err error)

Start powers on this VM.

func (*VM) Suspend

func (vm *VM) Suspend() (err error)

Suspend suspends this VM.

func (*VM) ValidateAuth

func (vm *VM) ValidateAuth() error

ValidateAuth: returns error if vcenter credentials are incorrect

type VMInfo

type VMInfo struct {
	VMId               string
	InstanceId         string
	IpAddress          []net.IP
	ToolsRunningStatus bool
	ToolsInstalled     bool
	OverallCpuUsage    int64
	GuestMemoryUsage   int64
	MaxCpuUsage        int32
	MaxMemoryUsage     int32
	NumCpu             int32
	PowerState         string
	MemorySizeMB       int32
	DisksInfo          []Disk
	NicInfo            []VirtualEthernetCard `json:"nic_info"`
}

type VMSearchFilter

type VMSearchFilter struct {
	Name         string
	InstanceUuid string
	SearchInDC   bool
}

VMSearchFilter struct encapsulates all relevant search parameters

type VMwareLease

type VMwareLease struct {
	Ctx   context.Context
	Lease *object.HttpNfcLease
}

VMwareLease implements the Lease interface.

func (VMwareLease) Complete

func (v VMwareLease) Complete() error

Complete marks the underlying lease as complete.

func (VMwareLease) HTTPNfcLeaseProgress

func (v VMwareLease) HTTPNfcLeaseProgress(p int32)

HTTPNfcLeaseProgress takes a percentage as an int and sets that percentage as the completed percent.

func (VMwareLease) Wait

func (v VMwareLease) Wait() (*types.HttpNfcLeaseInfo, error)

Wait waits for the underlying lease to finish.

type VirtualEthernetCard

type VirtualEthernetCard struct {
	NetworkName string `json:"network_name"`
	MacAddress  string `json:"mac_address"`
	NicName     string `json:"nic_name"`
	DeviceKey   int32  `json:"device_key"`
}

type VmProperties

type VmProperties struct {
	Name       string
	Properties mo.VirtualMachine
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL