util

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2025 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const GuestInfoBootstrapCondition = "guestinfo.vmservice.bootstrap.condition"

GuestInfoBootstrapCondition is the ExtraConfig key at which possible info about the bootstrap status may be stored.

View Source
const (
	// XsiNamespace indicates the XML schema instance namespace.
	XsiNamespace = "http://www.w3.org/2001/XMLSchema-instance"
)

Variables

This section is empty.

Functions

func Base64Decode

func Base64Decode(src []byte) ([]byte, error)

Base64Decode returns a byte slice decoded from a base64 byte slice.

func CNSAttachmentNameForVolume added in v1.8.6

func CNSAttachmentNameForVolume(vmName, volumeName string) string

CNSAttachmentNameForVolume returns the name of the CnsNodeVmAttachment based on the VM and Volume name. This matches the naming used in previous code but there are situations where we may get a collision between VMs and Volume names. I'm not sure if there is an absolute way to avoid that: the same situation can happen with the claimName. Ideally, we would use GenerateName, but we lack the back-linkage to match Volumes and CnsNodeVmAttachment up. The VM webhook validate that this result will be a valid k8s name.

func CopyStorageControllersAndDisks added in v1.9.0

func CopyStorageControllersAndDisks(
	dst *vimtypes.VirtualMachineConfigSpec,
	src vimtypes.VirtualMachineConfigSpec,
	storagePolicyID string)

CopyStorageControllersAndDisks copies the storage controllers and disks from the source spec to the destination. This function does not attempt to handle any conflicts -- it is a blind copy. If the provided storagePolicyID is non-empty, it is assigned to any all the copied disks.

func DatastoreNameFromStorageURI added in v1.9.0

func DatastoreNameFromStorageURI(s string) string

DatastoreNameFromStorageURI returns the datastore name from a storage URI, ex.: [my-datastore-1] vm-name/vm-name.vmx. The previous URI would return the value "my-datastore-1". An empty string is returned if there is no match.

func Dedupe added in v1.9.0

func Dedupe[T comparable](slice []T) []T

func DevicesFromConfigSpec

func DevicesFromConfigSpec(
	configSpec *vimtypes.VirtualMachineConfigSpec,
) []vimtypes.BaseVirtualDevice

DevicesFromConfigSpec returns a slice of devices from the ConfigSpec's DeviceChange property.

func EncodeGzipBase64 added in v1.8.5

func EncodeGzipBase64(s string) (string, error)

EncodeGzipBase64 compresses the input string using gzip and then encodes it using base64.

func EnsureDisksHaveControllers added in v1.9.0

func EnsureDisksHaveControllers(
	configSpec *vimtypes.VirtualMachineConfigSpec,
	existingDevices ...vimtypes.BaseVirtualDevice) error

EnsureDisksHaveControllers ensures that all disks in the provided ConfigSpec point to a controller. If no controller exists, new (in order of preference) PVSCSI, AHCI, or NVME controllers are added to the ConfigSpec as necessary for the disks.

Please note the following table for the number of controllers of each type that are supported as well as how many disks (per controller) each supports:

SATA

  • controllers 4
  • disks 30

SCSI

  • controllers 4
  • disks (non-paravirtual) 16
  • disks (paravirtual, hardware version <14) 16
  • disks (paravirtual, hardware version >=14) 256

NVME

  • controllers 4
  • disks (hardware version <20) 15
  • disks (hardware version >=21) 255

func EnsureMinHardwareVersionInConfigSpec added in v1.8.5

func EnsureMinHardwareVersionInConfigSpec(
	configSpec *vimtypes.VirtualMachineConfigSpec,
	minVersion int32)

EnsureMinHardwareVersionInConfigSpec ensures that the hardware version in the ConfigSpec is at least equal to the passed minimum hardware version value.

func FormatValue added in v1.9.0

func FormatValue(str string) (string, error)

func GetBootstrapConditionValues added in v1.8.6

func GetBootstrapConditionValues(
	configInfo *vimtypes.VirtualMachineConfigInfo) (bool, string, string, bool)

GetBootstrapConditionValues returns the bootstrap condition values from a VM if the data is present.

func GetSecretData added in v1.8.6

func GetSecretData(
	ctx context.Context,
	k8sClient ctrlclient.Client,
	secretNamespace, secretName, secretKey string,
	out *string) error

func GetSecretResource added in v1.8.6

func GetSecretResource(
	ctx context.Context,
	k8sClient ctrlclient.Client,
	secretNamespace, secretName string) (*corev1.Secret, error)

func HasDeviceChangeDeviceByType added in v1.8.6

func HasDeviceChangeDeviceByType[T vimtypes.BaseVirtualDevice](
	deviceChanges []vimtypes.BaseVirtualDeviceConfigSpec,
) bool

HasDeviceChangeDeviceByType returns true of one of the device change's dev is that of type T.

func HasVirtualPCIPassthroughDeviceChange added in v1.8.6

func HasVirtualPCIPassthroughDeviceChange(
	devices []vimtypes.BaseVirtualDeviceConfigSpec,
) bool

HasVirtualPCIPassthroughDeviceChange returns true if any of the device changes are for a passthrough device.

func IsDeviceDynamicDirectPathIO

func IsDeviceDynamicDirectPathIO(dev vimtypes.BaseVirtualDevice) bool

IsDeviceDynamicDirectPathIO returns true if the provided device is a dynamic direct path I/O device.

func IsDeviceNvidiaVgpu added in v1.8.3

func IsDeviceNvidiaVgpu(dev vimtypes.BaseVirtualDevice) bool

IsDeviceNvidiaVgpu returns true if the provided device is an Nvidia vGPU.

func IsEthernetCard

func IsEthernetCard(dev vimtypes.BaseVirtualDevice) bool

func IsNil added in v1.9.0

func IsNil(v any) bool

IsNil returns true if v is nil, including a nil check against possible interface data.

func IsNotFoundError added in v1.8.6

func IsNotFoundError(err error) bool

func IsValidDomainName added in v1.9.0

func IsValidDomainName(s string) bool

IsValidDomainName returns true if the provided value adheres to the format for DNS names specified in RFC-1034, Section 3.5:

  • must not exceed 255 characters in length when combined with the host name
  • individual segments must be 63 characters or less.
  • the top-level domain( ex. ".com"), is at least two letters with no special characters.
  • underscores are not allowed.
  • dashes are permitted, but not at the start or end of the value.
  • long, top-level domain names (ex. ".london") are permitted.
  • symbol unicode points, such as emoji, are disallowed in the top-level domain.

Please refer to the comments for the IsValidHostName function for information on why both functions were defined as part of this project instead of using existing functions from the Kubernetes API machinery project or OpenAPI's validation utility functions.

func IsValidHostName added in v1.9.0

func IsValidHostName(s string) bool

IsValidHostName returns true if the provided value adheres to the format of an RFC-1123 DNS label, which may be:

  • an IP4 address
  • an IP6 address
  • a string of alpha-numeric characters that:
  • must not exceed 63 characters in length
  • may begin with a digit
  • may contain dashes except as the first or last character
  • must not contain underscores
  • may contain symbol-point unicode, (ex. emoji)

The IsValidHostName and IsValidDomainName functions are defined as part of this project because the similar functions from the Kubernetes API machinery and OpenAPI projects were different enough to not be compatible with the type of required validation.

Since none of the above, upstream functions could be re-used as-is, instead the regular expression HostnamePattern from https://github.com/go-openapi/strfmt/blob/f065ed8a46434a6407610166cd707c170cf1e483/default.go#L33-L60C21 was used as the basis for this file's hostNameFormat and fqdnFormat regular expressions. Additionally, the level of testing in network_test.go for both the IsValidHostName and IsValidDomainName functions far exceeds the testing for the aforementioned, upstream functions.

func MarshalConfigSpecToJSON

func MarshalConfigSpecToJSON(
	configSpec vimtypes.VirtualMachineConfigSpec) ([]byte, error)

MarshalConfigSpecToJSON returns a byte slice of the provided ConfigSpec marshaled to a JSON string.

func MarshalConfigSpecToXML

func MarshalConfigSpecToXML(
	configSpec vimtypes.VirtualMachineConfigSpec) ([]byte, error)

MarshalConfigSpecToXML returns a byte slice of the provided ConfigSpec marshalled to an XML string.

func MustFormatValue added in v1.9.0

func MustFormatValue(str string) string

MustFormatValue returns the passed value if it meets the standards for a Kubernetes label value. Otherwise, it returns a hash which meets the requirements. A copy of the method used by cluster-api for MachineSets.

func RemoveDevicesFromConfigSpec

func RemoveDevicesFromConfigSpec(configSpec *vimtypes.VirtualMachineConfigSpec, fn func(vimtypes.BaseVirtualDevice) bool)

RemoveDevicesFromConfigSpec removes devices from config spec device changes based on the matcher function.

func SafeConfigSpecToString added in v1.9.0

func SafeConfigSpecToString(
	in *vimtypes.VirtualMachineConfigSpec) (s string)

SafeConfigSpecToString returns the string-ified version of the provided ConfigSpec, first trying to use the special JSON encoder, then defaulting to the normal JSON encoder.

Please note, this function is not intended to replace marshaling the data to JSON using the normal workflows. This function is for when a string-ified version of the data is needed for things like logging.

func SanitizeVMClassConfigSpec

func SanitizeVMClassConfigSpec(
	ctx context.Context,
	configSpec *vimtypes.VirtualMachineConfigSpec)

SanitizeVMClassConfigSpec clears fields in the class ConfigSpec that are not allowed or supported.

func SelectDevices

func SelectDevices[T vimtypes.BaseVirtualDevice](
	devices []vimtypes.BaseVirtualDevice,
	selectorFns ...SelectDeviceFn[T],
) []T

SelectDevices returns a slice of the devices that match at least one of the provided selector functions.

func SelectDevicesByBackingType

func SelectDevicesByBackingType[B vimtypes.BaseVirtualDeviceBackingInfo](
	devices []vimtypes.BaseVirtualDevice,
) []vimtypes.BaseVirtualDevice

SelectDevicesByBackingType returns a slice of the devices that have a backing of type B.

func SelectDevicesByDeviceAndBackingType

func SelectDevicesByDeviceAndBackingType[
	T vimtypes.BaseVirtualDevice,
	B vimtypes.BaseVirtualDeviceBackingInfo,
](
	devices []vimtypes.BaseVirtualDevice,
) []T

SelectDevicesByDeviceAndBackingType returns a slice of the devices that are of type T with a backing of type B.

func SelectDevicesByType

func SelectDevicesByType[T vimtypes.BaseVirtualDevice](
	devices []vimtypes.BaseVirtualDevice,
) []T

SelectDevicesByType returns a slice of the devices that are of type T.

func SelectDevicesByTypes

func SelectDevicesByTypes(
	devices []vimtypes.BaseVirtualDevice,
	deviceTypes ...vimtypes.BaseVirtualDevice,
) []vimtypes.BaseVirtualDevice

SelectDevicesByTypes returns a slice of the devices that match at least one the provided device types.

func SelectDynamicDirectPathIO

func SelectDynamicDirectPathIO(
	devices []vimtypes.BaseVirtualDevice,
) []*vimtypes.VirtualPCIPassthrough

SelectDynamicDirectPathIO returns a slice of dynamic direct path I/O devices.

func SelectNvidiaVgpu added in v1.8.3

func SelectNvidiaVgpu(
	devices []vimtypes.BaseVirtualDevice,
) []*vimtypes.VirtualPCIPassthrough

SelectNvidiaVgpu return a slice of Nvidia vGPU devices.

func SelectVirtualPCIPassthrough

func SelectVirtualPCIPassthrough(
	devices []vimtypes.BaseVirtualDevice,
) []*vimtypes.VirtualPCIPassthrough

SelectVirtualPCIPassthrough returns a slice of *VirtualPCIPassthrough devices.

func TryToDecodeBase64Gzip

func TryToDecodeBase64Gzip(data []byte) (string, error)

TryToDecodeBase64Gzip base64-decodes the provided data until the DecodeString function fails. If the result is gzipped, then it is decompressed and returned. Otherwise the decoded data is returned.

This function will also return the original data as a string if it was neither base64 encoded or gzipped.

func UnmarshalConfigSpecFromBase64XML

func UnmarshalConfigSpecFromBase64XML(
	src []byte) (vimtypes.VirtualMachineConfigSpec, error)

UnmarshalConfigSpecFromBase64XML returns a ConfigSpec object from a byte-slice of the ConfigSpec marshaled as a base64-encoded, XML string.

func UnmarshalConfigSpecFromJSON

func UnmarshalConfigSpecFromJSON(
	data []byte) (vimtypes.VirtualMachineConfigSpec, error)

UnmarshalConfigSpecFromJSON returns a ConfigSpec object from a byte-slice of the ConfigSpec marshaled as a JSON string.

func UnmarshalConfigSpecFromXML

func UnmarshalConfigSpecFromXML(
	data []byte) (vimtypes.VirtualMachineConfigSpec, error)

UnmarshalConfigSpecFromXML returns a ConfigSpec object from a byte-slice of the ConfigSpec marshaled as an XML string.

func WithVAPIActivationID added in v1.9.0

func WithVAPIActivationID(
	ctx context.Context,
	client *rest.Client,
	id string) context.Context

WithVAPIActivationID adds the specified id to the context to be used as the VAPI REST client's activation ID -- the value assigned to the activationId field to the vim.Task the VAPI API may spawn.

Types

type Cache added in v1.8.1

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache is a generic implementation of a cache that can be configured with a maximum number of items and can evict items after a certain amount of time.

func NewCache added in v1.8.1

func NewCache[T any](
	expireAfter, checkExpireInterval time.Duration,
	maxItems int) *Cache[T]

NewCache initializes a new cache with the provided expiration options.

func (*Cache[T]) Close added in v1.8.1

func (c *Cache[T]) Close()

Close shuts down the cache. It is safe to call this function more than once.

func (*Cache[T]) Delete added in v1.8.1

func (c *Cache[T]) Delete(id string)

Delete removes the specified item from the cache.

func (*Cache[T]) ExpiredChan added in v1.8.1

func (c *Cache[T]) ExpiredChan() <-chan string

ExpiredChan returns a channel on which the IDs of items that are expired are sent. This channel is closed when the cache is closed, but only after all, pending eviction notices are received.

func (*Cache[T]) Get added in v1.8.1

func (c *Cache[T]) Get(id string, isHit func(t T) bool) (T, bool)

Get returns the cached item with the provided ID. The function isHit may be optionally provided to further determine whether a cached item should hit or miss.

func (*Cache[T]) Put added in v1.8.1

func (c *Cache[T]) Put(id string, t T) CachePutResult

Put stores the provided item in the cache, updating existing items.

type CacheItem added in v1.8.1

type CacheItem[T any] struct {
	// Item is the cached item.
	Item T

	// LastUpdated is the last time the item was updated.
	LastUpdated time.Time
}

CacheItem wraps T so it has a LastUpdated field and can be used with Cache.

type CachePutResult added in v1.8.1

type CachePutResult uint

CachePutResult describes the result of putting an item into the cache.

const (
	// CachePutResultCreate indicates the item was created in the cache.
	CachePutResultCreate CachePutResult = iota + 1

	// CachePutResultUpdate indicates an existing, cached item was updated.
	CachePutResultUpdate

	// CachePutResultMaxItemsExceeded indicates the item was not stored because
	// the cache's maximum number of items would have been exceeded.
	CachePutResultMaxItemsExceeded
)

type LockPool added in v1.8.1

type LockPool[K any, V sync.Locker] struct {
	// contains filtered or unexported fields
}

LockPool is a synchronized set of maps that can be obtained with a provided ID.

func (*LockPool[K, V]) Delete added in v1.8.1

func (p *LockPool[K, V]) Delete(id K)

Delete removes the specified lock from the pool.

func (*LockPool[K, V]) Get added in v1.8.1

func (p *LockPool[K, V]) Get(id K) sync.Locker

Get returns the lock for the provided ID.

type OptionValues added in v1.9.0

type OptionValues []vimtypes.BaseOptionValue

OptionValues simplifies manipulation of properties that are arrays of vimtypes.BaseOptionValue, such as ExtraConfig.

func OptionValuesFromMap added in v1.9.0

func OptionValuesFromMap[T any](in map[string]T) OptionValues

OptionValuesFromMap returns a new OptionValues object from the provided map.

func (OptionValues) Additions added in v1.9.0

func (ov OptionValues) Additions(in ...vimtypes.BaseOptionValue) OptionValues

Additions returns a diff that includes only the elements from the provided list that do not already exist.

func (OptionValues) Append added in v1.9.0

Append adds the provided item(s) as long as a key does not conflict with an existing item.

func (OptionValues) Delete added in v1.9.0

func (ov OptionValues) Delete(key string) OptionValues

Delete removes elements with the given key, returning the new list.

func (OptionValues) Diff added in v1.9.0

Diff returns a diff that includes the elements from the provided list that do not already exist or have different values.

func (OptionValues) Get added in v1.9.0

func (ov OptionValues) Get(key string) (any, bool)

Get returns the value if exists, otherwise nil is returned. The second return value is a flag indicating whether the value exists or nil was the actual value.

func (OptionValues) GetString added in v1.9.0

func (ov OptionValues) GetString(key string) (string, bool)

GetString returns the value as a string if the value exists.

func (OptionValues) Map added in v1.9.0

func (ov OptionValues) Map() map[string]any

Map returns the list of option values as a map.

func (OptionValues) Merge added in v1.9.0

Merge adds the provided item(s), overwriting any existing values.

func (OptionValues) StringMap added in v1.9.0

func (ov OptionValues) StringMap() map[string]string

StringMap returns the list of option values as a map where the values are strings.

type SelectDeviceFn

type SelectDeviceFn[T vimtypes.BaseVirtualDevice] func(dev vimtypes.BaseVirtualDevice) bool

SelectDeviceFn returns true if the provided virtual device is a match.

Jump to

Keyboard shortcuts

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