utils

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2022 License: Apache-2.0 Imports: 50 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Linux is a constant value for the runtime.GOOS that represents the Linux OS
	Linux = "linux"

	// Windows is a constant value for the runtime.GOOS that represents the Windows OS
	Windows = "windows"

	// Darwin is a constant value for the runtime.GOOS that represents Apple MacOS
	Darwin = "darwin"

	PrepPending       NodePrepStatus = "pending"
	PrepRunning       NodePrepStatus = "running"
	PrepCompleted     NodePrepStatus = "completed"
	PrepFailed        NodePrepStatus = "failed"
	PrepOutdated      NodePrepStatus = "outdated"
	PrepPreConfigured NodePrepStatus = "preconfigured"

	Centos = "centos"
	RHEL   = "rhel"
	Ubuntu = "ubuntu"
	Debian = "debian"

	REDACTED = "<REDACTED>"

	// NAS protocols
	SMB = "smb"
)

Variables

View Source
var (
	NFSVersionMajorRegex      = regexp.MustCompile(`^(nfsvers|vers)=(?P<major>\d)$`)
	NFSVersionMajorMinorRegex = regexp.MustCompile(`^(nfsvers|vers)=(?P<major>\d)\.(?P<minor>\d)$`)
	NFSVersionMinorRegex      = regexp.MustCompile(`^minorversion=(?P<minor>\d)$`)
)

Functions

func AppendToStringList

func AppendToStringList(stringList, newItem, sep string) string

AppendToStringList appends an item to a string list with a seperator

func AreMountOptionsInList

func AreMountOptionsInList(mountOptions string, optionList []string) bool

AreMountOptionsInList returns true if any of the options are in mountOptions

func AttachBlockOnFileVolume

func AttachBlockOnFileVolume(
	ctx context.Context, mountPath string, publishInfo *VolumePublishInfo,
) (string, string, error)

func AttachISCSIVolume

func AttachISCSIVolume(ctx context.Context, name, mountpoint string, publishInfo *VolumePublishInfo, secrets map[string]string) error

AttachISCSIVolume attaches the volume to the local host. This method must be able to accomplish its task using only the data passed in. It may be assumed that this method always runs on the host to which the volume will be attached. If the mountpoint parameter is specified, the volume will be mounted. The device path is set on the in-out publishInfo parameter so that it may be mounted later instead.

func AttachISCSIVolumeRetry

func AttachISCSIVolumeRetry(
	ctx context.Context, name, mountpoint string, publishInfo *VolumePublishInfo, secrets map[string]string, timeout time.Duration,
) error

AttachISCSIVolumeRetry attaches a volume with retry by invoking AttachISCSIVolume with backoff.

func AttachNFSVolume

func AttachNFSVolume(ctx context.Context, name, mountpoint string, publishInfo *VolumePublishInfo) error

AttachNFSVolume attaches the volume to the local host. This method must be able to accomplish its task using only the data passed in. It may be assumed that this method always runs on the host to which the volume will be attached.

func AttachSMBVolume

func AttachSMBVolume(
	ctx context.Context, name, mountpoint, username, password string, publishInfo *VolumePublishInfo,
) error

func AuthError

func AuthError(message string) error

func BootstrapError

func BootstrapError(err error) error

func CheckMountOptions

func CheckMountOptions(ctx context.Context, procMount MountInfo, mountOptions string) error

CheckMountOptions check if the new mount options are different from already mounted options. Return an error if there is mismatch with the mount options.

func ConsistentRead

func ConsistentRead(filename string, attempts int) ([]byte, error)

ConsistentRead repeatedly reads a file until it gets the same content twice. This is useful when reading files in /proc that are larger than page size and kernel may modify them between individual read() syscalls.

func ConvertSizeToBytes

func ConvertSizeToBytes(s string) (string, error)

ConvertSizeToBytes converts size to bytes; see also https://en.wikipedia.org/wiki/Kilobyte

func ConvertToReconcileIncompleteError

func ConvertToReconcileIncompleteError(err error) error

func CountSpacesBeforeText

func CountSpacesBeforeText(text string) int

func DecryptStringWithAES

func DecryptStringWithAES(encryptedText string, key []byte) (string, error)

DecryptStringWithAES takes an encrypted, base64-encoded string and a key and returns the plaintext form of the string

func DeleteResourceAtPath

func DeleteResourceAtPath(ctx context.Context, resource string) error

DeleteResourceAtPath makes sure that given named file or (empty) directory is removed

func DetachBlockOnFileVolume

func DetachBlockOnFileVolume(ctx context.Context, loopDevice, loopFile string) error

func EncryptStringWithAES

func EncryptStringWithAES(plainText string, key []byte) (string, error)

EncryptStringWithAES takes a string and a key and returns the encrypted, base64-encoded form of the string

func EnsureDirExists

func EnsureDirExists(ctx context.Context, path string) error

EnsureDirExists makes sure that given directory structure exists

func EnsureFileExists

func EnsureFileExists(ctx context.Context, path string) error

EnsureFileExists makes sure that file of given name exists

func EnsureISCSISessionWithPortalDiscovery

func EnsureISCSISessionWithPortalDiscovery(ctx context.Context, hostDataIP string) error

func EnsureISCSISessions

func EnsureISCSISessions(ctx context.Context, publishInfo *VolumePublishInfo, portals []string) (bool, error)

EnsureISCSISessions this is to make sure that Trident establishes iSCSI sessions with the given list of portals

func EnsureISCSISessionsWithPortalDiscovery

func EnsureISCSISessionsWithPortalDiscovery(ctx context.Context, hostDataIPs []string) error

func EnsureLUKSDevice

func EnsureLUKSDevice(ctx context.Context, device, volumeId, luksPassphrase string) (bool, string, error)

EnsureLUKSDevice ensures the specified device is LUKS formatted and opened, returns whether a luksFormat of the device was needed

func EnsureLUKSDeviceClosed

func EnsureLUKSDeviceClosed(ctx context.Context, luksDevicePath string) error

EnsureLUKSDeviceClosed ensures there is not an open LUKS device at the specified path

func ExpandFilesystemOnNode

func ExpandFilesystemOnNode(
	ctx context.Context, publishInfo *VolumePublishInfo, stagedTargetPath, fsType, mountOptions string,
) (int64, error)

ExpandFilesystemOnNode will expand the filesystem of an already expanded volume.

func FilterIPs

func FilterIPs(ctx context.Context, ips, cidrs []string) ([]string, error)

FilterIPs takes a list of IPs and CIDRs and returns the sorted list of IPs that are contained by one or more of the CIDRs

func FoundError

func FoundError(message string) error

func GenerateAESKey

func GenerateAESKey() (string, error)

GenerateAESKey generates a cryptographically random 32-byte key, returned as a base64-encoded string

func GenerateVolumePublishName

func GenerateVolumePublishName(volumeID, nodeID string) string

func GetAllLoopDeviceBackFiles

func GetAllLoopDeviceBackFiles(ctx context.Context) ([]string, error)

func GetDeviceFilePath

func GetDeviceFilePath(ctx context.Context, path, volumeId string) (string, error)

GetDeviceFilePath returns the staging path for volume.

func GetDeviceNameFromMount

func GetDeviceNameFromMount(ctx context.Context, mountpath string) (string, int, error)

func GetFilesystemStats

func GetFilesystemStats(
	ctx context.Context, path string,
) (available, capacity, usage, inodes, inodesFree, inodesUsed int64, err error)

GetFilesystemStats returns the size of the filesystem for the given path. The caller of the func is responsible for verifying the mountPoint existence and readiness.

func GetFindMultipathValue

func GetFindMultipathValue(text string) string

GetFindMultipathValue returns the value of find_multipaths Returned values: no (or off): Create a multipath device for every path that is not explicitly disabled yes (or on): Create a device if one of some conditions are met other possible values: smart, greedy, strict

func GetIPAddresses

func GetIPAddresses(ctx context.Context) ([]string, error)

GetIPAddresses returns the sorted list of Global Unicast IP addresses available to Trident

func GetISCSIHostSessionMapForTarget

func GetISCSIHostSessionMapForTarget(ctx context.Context, iSCSINodeName string) map[int]int

GetISCSIHostSessionMapForTarget returns a map of iSCSI host numbers to iSCSI session numbers for a given iSCSI target.

func GetInitiatorIqns

func GetInitiatorIqns(ctx context.Context) ([]string, error)

GetInitiatorIqns returns parsed contents of /etc/iscsi/initiatorname.iscsi

func GetMountedLoopDevices

func GetMountedLoopDevices(ctx context.Context) ([]string, error)

GetMountedLoopDevices returns a list of loop devices that are *mounted* on this host.

func GetNFSVersionFromMountOptions

func GetNFSVersionFromMountOptions(mountOptions, defaultVersion string, supportedVersions []string) (string, error)

GetNFSVersionFromMountOptions accepts a set of mount options, a default NFS version, and a list of supported NFS versions, and it returns the NFS version specified by the mount options, or the default if none is found, plus an error (if any). If a set of supported versions is supplied, and the returned version isn't in it, this method returns an error; otherwise it returns nil.

func GetNFSVersionMountOptions

func GetNFSVersionMountOptions(mountOptions string) []string

GetNFSVersionMountOptions accepts a set of mount options, identifies and returns all of the NFS version mount options.

func GetPrintableBoolPtrValue

func GetPrintableBoolPtrValue(bPtr *bool) string

func GetRandomNumber

func GetRandomNumber(max int) int

GetRandomNumber will generate a cryptographically secure random number in the range of [0, max)

func GetRegexSubmatches

func GetRegexSubmatches(r *regexp.Regexp, s string) map[string]string

GetRegexSubmatches accepts a regular expression with one or more groups and returns a map of the group matches found in the supplied string.

func GetTargetFilePath

func GetTargetFilePath(ctx context.Context, resourcePath, arg string) string

GetTargetFilePath method returns the path of target file based on OS.

func GetUnmountPath

func GetUnmountPath(ctx context.Context, resourcePath, arg string) (string, error)

GetUnmountPath is a dummy added for compilation

func GetV

func GetV(opts map[string]string, keys, defaultValue string) string

GetV takes a map, key(s), and a defaultValue; will return the value of the key or defaultValue if none is set. If keys is a string of key values separated by "|", then each key is tried in turn. This allows compatibility with deprecated values, i.e. "fstype|fileSystemType".

func GetVerifiedBlockFsType

func GetVerifiedBlockFsType(filesystemType string) (string, error)

GetVerifiedBlockFsType retrieves and verifies the filesystem type for a BlockOnFile protocol

func GetVolumeSizeBytes

func GetVolumeSizeBytes(ctx context.Context, opts map[string]string, defaultVolumeSize string) (uint64, error)

GetVolumeSizeBytes determines the size, in bytes, of a volume from the "size" opt value. If "size" has a units suffix, that is handled here. If there are no units, the default is GiB. If size is not in opts, the specified default value is parsed identically and used instead.

func GetYAMLTagWithSpaceCount

func GetYAMLTagWithSpaceCount(text, tagName string) (string, int)

func HasUnsupportedCapacityRangeError

func HasUnsupportedCapacityRangeError(err error) (bool, *unsupportedCapacityRangeError)

func IPv6Check

func IPv6Check(ip string) bool

func ISCSIActiveOnHost

func ISCSIActiveOnHost(ctx context.Context, host HostSystem) (bool, error)

ISCSIActiveOnHost will return if the iscsi daemon is active on the given host

func ISCSILogout

func ISCSILogout(ctx context.Context, targetIQN, targetPortal string) error

ISCSILogout logs out from the supplied target

func ISCSIRescanDevices

func ISCSIRescanDevices(ctx context.Context, targetIQN string, lunID int32, minSize int64) error

func ISCSISupported

func ISCSISupported(ctx context.Context) bool

ISCSISupported returns true if iscsiadm is installed and in the PATH.

func ISCSITargetHasMountedDevice

func ISCSITargetHasMountedDevice(ctx context.Context, targetIQN string) (bool, error)

ISCSITargetHasMountedDevice returns true if this host has any mounted devices on the specified target.

func InvalidInputError

func InvalidInputError(message string) error

func IsAlreadyAttached

func IsAlreadyAttached(ctx context.Context, lunID int, targetIqn string) bool

IsAlreadyAttached checks if there is already an established iSCSI session to the specified LUN.

func IsAuthError

func IsAuthError(err error) bool

func IsBootstrapError

func IsBootstrapError(err error) bool

func IsCompatible

func IsCompatible(ctx context.Context, protocol string) error

IsCompatible checks for compatibility of protocol and platform

func IsFoundError

func IsFoundError(err error) bool

func IsInvalidInputError

func IsInvalidInputError(err error) bool

func IsLUKSDeviceOpen

func IsLUKSDeviceOpen(ctx context.Context, luksDevicePath string) (bool, error)

IsLUKSDeviceOpen returns whether the specific LUKS device is currently open

func IsLikelyDir

func IsLikelyDir(mountpoint string) (bool, error)

IsLikelyDir determines if mountpoint is a directory

func IsLikelyNotMountPoint

func IsLikelyNotMountPoint(ctx context.Context, mountpoint string) (bool, error)

IsLikelyNotMountPoint uses heuristics to determine if a directory is not a mountpoint. It should return ErrNotExist when the directory does not exist. IsLikelyNotMountPoint does NOT properly detect all mountpoint types most notably Linux bind mounts and symbolic links. For callers that do not care about such situations, this is a faster alternative to scanning the list of mounts. A return value of false means the directory is definitely a mount point. A return value of true means it's not a mount this function knows how to find, but it could still be a mount point.

func IsLoopDeviceAttachedToFile

func IsLoopDeviceAttachedToFile(ctx context.Context, loopDevice, loopFile string) (bool, error)

func IsLoopDeviceMounted

func IsLoopDeviceMounted(ctx context.Context, deviceName string) (mounted bool, err error)

IsLoopDeviceMounted returns true if loop device is mounted

func IsMaxLimitReachedError

func IsMaxLimitReachedError(err error) bool

func IsMounted

func IsMounted(ctx context.Context, sourceDevice, mountpoint, mountOptions string) (bool, error)

IsMounted verifies if the supplied device is attached at the supplied location. IsMounted checks whether the specified device is attached at the given mountpoint. If no source device is specified, any existing mount with the specified mountpoint returns true. If no mountpoint is specified, any existing mount with the specified device returns true.

func IsNFSShareMounted

func IsNFSShareMounted(ctx context.Context, exportPath, mountpoint string) (bool, error)

func IsNotFoundError

func IsNotFoundError(err error) bool

func IsNotReadyError

func IsNotReadyError(err error) bool

func IsReconcileDeferredError

func IsReconcileDeferredError(err error) bool

func IsReconcileFailedError

func IsReconcileFailedError(err error) bool

func IsReconcileIncompleteError

func IsReconcileIncompleteError(err error) bool

func IsResourceNotFoundError

func IsResourceNotFoundError(err error) bool

func IsTempOperatorError

func IsTempOperatorError(err error) bool

func IsTimeoutError

func IsTimeoutError(err error) bool

func IsTooManyRequestsError

func IsTooManyRequestsError(err error) bool

func IsUnsupportedConfigError

func IsUnsupportedConfigError(err error) bool

func IsUnsupportedError

func IsUnsupportedError(err error) bool

func IsUnsupportedKubernetesVersionError

func IsUnsupportedKubernetesVersionError(err error) bool

func IsVolumeCreatingError

func IsVolumeCreatingError(err error) bool

func IsVolumeDeletingError

func IsVolumeDeletingError(err error) bool

func Lock

func Lock(ctx context.Context, lockContext, lockID string)

Lock acquires a mutex with the specified ID. The mutex does not need to exist before calling this method. The semantics of this method are intentionally identical to sync.Mutex.Lock().

func LogHTTPRequest

func LogHTTPRequest(request *http.Request, requestBody []byte, redactBody bool)

func LogHTTPResponse

func LogHTTPResponse(ctx context.Context, response *http.Response, responseBody []byte, redactBody bool)

func Max

func Max(x, y int64) int64

func MaxLimitReachedError

func MaxLimitReachedError(message string) error

func MinInt64

func MinInt64(a, b int64) int64

MinInt64 returns the lower of the two integers specified

func MountDevice

func MountDevice(ctx context.Context, device, mountpoint, options string, isMountPointFile bool) (err error)

MountDevice attaches the supplied device at the supplied location. Use this for iSCSI devices.

func NFSActiveOnHost

func NFSActiveOnHost(ctx context.Context) (bool, error)

NFSActiveOnHost will return if the rpc-statd daemon is active on the given host

func NotFoundError

func NotFoundError(message string) error

func NotReadyError

func NotReadyError() error

func PKCS7Pad

func PKCS7Pad(input []byte, blockSize int) []byte

PKCS7Pad will pad the input to a multiple of blocksize according to PKCS#7 standard

func PKCS7Unpad

func PKCS7Unpad(input []byte) ([]byte, error)

PKCS7Pad will remove the padding from input according to PKCS#7 standard

func PathExists

func PathExists(path string) (bool, error)

func Pow

func Pow(x int64, y int) int64

Pow is an integer version of exponentiation; existing builtin is float, we needed an int version.

func PrepareDeviceAtMountPathForRemoval

func PrepareDeviceAtMountPathForRemoval(ctx context.Context, mountpoint string, unmount, unsafe, force bool) error

PrepareDeviceAtMountPathForRemoval informs Linux that a device will be removed.

func PrepareDeviceForRemoval

func PrepareDeviceForRemoval(ctx context.Context, lunID int, iSCSINodeName string, unsafe, force bool) error

PrepareDeviceForRemoval informs Linux that a device will be removed.

func RandomString

func RandomString(strSize int) string

RandomString returns a string of the specified length consisting only of alphabetic characters.

func ReconcileDeferredError

func ReconcileDeferredError(err error) error

func ReconcileFailedError

func ReconcileFailedError(err error) error

func ReconcileIncompleteError

func ReconcileIncompleteError() error

func RedactSecretsFromString

func RedactSecretsFromString(stringToSanitize string, replacements map[string]string, useRegex bool) string

func RemountDevice

func RemountDevice(ctx context.Context, mountpoint, options string) (err error)

RemountDevice remounts the mountpoint with supplied mount options.

func RemoveMountPoint

func RemoveMountPoint(ctx context.Context, mountPointPath string) error

RemoveMountPoint attempts to unmount and remove the directory of the mountPointPath. This method should be idempotent and safe to call again if it fails the first time.

func RemoveMountPointRetry

func RemoveMountPointRetry(ctx context.Context, mountPointPath string) error

RemoveMountPointRetry attempts to unmount and remove the directory of the mountPointPath. This method should be idempotent and safe to call again if it fails the first time.

func RemoveStringFromSlice

func RemoveStringFromSlice(slice []string, s string) (result []string)

RemoveStringFromSlice removes a string from a []string

func RemoveStringFromSliceConditionally

func RemoveStringFromSliceConditionally(slice []string, s string, fn func(string, string) bool) (result []string)

RemoveStringFromSliceConditionally removes a string from a []string if it meets certain criteria

func ReplaceAtIndex

func ReplaceAtIndex(in string, r rune, index int) (string, error)

ReplaceAtIndex returns a string with the rune at the specified index replaced

func ReplaceImageRegistry

func ReplaceImageRegistry(image, registry string) string

ReplaceImageRegistry accepts a container image name and a registry name (FQDN[:port]) and returns the same image name with the supplied registry.

func ResizeLoopDevice

func ResizeLoopDevice(ctx context.Context, loopDevice, loopFile string, requiredBytes int64) error

func RunningInContainer

func RunningInContainer() bool

Detect if code is running in a container or not

func SMBActiveOnHost

func SMBActiveOnHost(ctx context.Context) (bool, error)

SMBActiveOnHost will always return false on non-windows platform

func SafeToLogOut

func SafeToLogOut(ctx context.Context, hostNumber, sessionNumber int) bool

SafeToLogOut looks for remaining block devices on a given iSCSI host, and returns true if there are none, indicating that logging out would be safe.

func SafeToRemoveNFSMount

func SafeToRemoveNFSMount(ctx context.Context, nfsMountPoint string) bool

SafeToRemoveNFSMount returns true if NFS mount point has any subvolumes in use by loop, if not returns true

func SanitizeMountOptions

func SanitizeMountOptions(mountOptions string, removeMountOptions []string) string

SanitizeMountOptions removes the options provided from the string list and spaces around options

func ServiceActiveOnHost

func ServiceActiveOnHost(ctx context.Context, service string) (bool, error)

ServiceActiveOnHost checks if the service is currently running

func SetChrootPathPrefix

func SetChrootPathPrefix(prefix string)

func SetNFSVersionMountOptions

func SetNFSVersionMountOptions(mountOptions, newNFSVersionMountOption string) string

SetNFSVersionMountOptions removes any existing NFS version mount option and sets passed NFS version mount options.

func SliceContains

func SliceContains(genericSlice, genericElement interface{}) bool

SliceContains checks to see if a slice (genericSlice) contains an item (genericElement)

func SliceContainsElements

func SliceContainsElements(genericSlice, genericElements interface{}) (bool, bool)

SliceContainsElements checks to see if a slice (genericSlice) contains a list of all/some items (genericElements)

func SliceContainsString

func SliceContainsString(slice []string, s string) bool

SliceContainsString checks to see if a []string contains a string

func SliceContainsStringCaseInsensitive

func SliceContainsStringCaseInsensitive(slice []string, s string) bool

SliceContainsStringCaseInsensitive is SliceContainsString but case insensitive

func SliceContainsStringConditionally

func SliceContainsStringConditionally(slice []string, s string, fn func(string, string) bool) bool

SliceContainsStringConditionally checks to see if a []string contains a string based on certain criteria

func SplitImageDomain

func SplitImageDomain(name string) (domain, remainder string)

SplitImageDomain accepts a container image name and splits off the domain portion, if any.

func SplitString

func SplitString(_ context.Context, s, sep string) []string

SplitString is same as strings.Split except it returns a nil ([]string(nil)) of size 0 instead of string slice with an empty string (size 1) when string to be split is empty.

func StringInSlice

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

StringInSlice checks whether a string is in a list of strings

func TempOperatorError

func TempOperatorError(err error) error

func TimeoutError

func TimeoutError(message string) error

func Title

func Title(str string) string

Title minimally replaces the deprecated strings.Title() function.

func ToStringRedacted

func ToStringRedacted(structPointer interface{}, redactList []string, configVal interface{}) (out string)

ToStringRedacted identifies attributes of a struct, stringifies them such that they can be consumed by the struct's stringer interface, and redacts elements specified in the redactList.

func TooManyRequestsError

func TooManyRequestsError(message string) error

func TypeAssertionError

func TypeAssertionError(assertion string) error

func Umount

func Umount(ctx context.Context, mountpoint string) (err error)

Umount detaches from the supplied location.

func UmountAndRemoveMountPoint

func UmountAndRemoveMountPoint(ctx context.Context, mountPoint string) error

UmountAndRemoveMountPoint unmounts and removes the mountPoint

func UmountAndRemoveTemporaryMountPoint

func UmountAndRemoveTemporaryMountPoint(ctx context.Context, mountPath string) error

UmountAndRemoveTemporaryMountPoint unmounts and removes the temporaryMountDir

func UmountSMBPath

func UmountSMBPath(ctx context.Context, mappingPath, target string) (err error)

UmountSMBPath is a dummy added for compilation on non-windows platform.

func Unlock

func Unlock(ctx context.Context, lockContext, lockID string)

Unlock releases a mutex with the specified ID. The semantics of this method are intentionally identical to sync.Mutex.Unlock().

func UnsupportedCapacityRangeError

func UnsupportedCapacityRangeError(err error) error

func UnsupportedConfigError

func UnsupportedConfigError(err error) error

func UnsupportedError

func UnsupportedError(message string) error

func UnsupportedKubernetesVersionError

func UnsupportedKubernetesVersionError(err error) error

func ValidateCIDRs

func ValidateCIDRs(ctx context.Context, cidrs []string) error

ValidateCIDRs checks if a list of CIDR blocks are valid and returns a multi error containing all errors which may occur during the parsing process.

func ValidateOctalUnixPermissions

func ValidateOctalUnixPermissions(perms string) error

func VerifyFilesystemSupport

func VerifyFilesystemSupport(fs string) (string, error)

VerifyFilesystemSupport checks for a supported file system type

func VolumeCreatingError

func VolumeCreatingError(message string) error

func VolumeDeletingError

func VolumeDeletingError(message string) error

func VolumeSizeWithinTolerance

func VolumeSizeWithinTolerance(requestedSize, currentSize, delta int64) (bool, error)

VolumeSizeWithinTolerance checks to see if requestedSize is within the delta of the currentSize. If within the delta true is returned. If not within the delta and requestedSize is less than the currentSize false is returned.

func WaitForLoopDeviceDetach

func WaitForLoopDeviceDetach(
	ctx context.Context, nfsMountpoint, loopFile string, maxDuration time.Duration,
) error

WaitForLoopDeviceDetach waits until a loop device is detached from the specified NFS mountpoint, and it returns the remaining number of attached devices.

func WaitForResourceDeletionAtPath

func WaitForResourceDeletionAtPath(ctx context.Context, resource string, maxDuration time.Duration) error

WaitForResourceDeletionAtPath accepts a resource name and waits until it is deleted and returns error if it times out

func WindowsBindMount

func WindowsBindMount(ctx context.Context, source, target string, options []string) (err error)

WindowsBindMount is a dummy added for compilation on non-windows platform.

Types

type CSIProxyUtils

type CSIProxyUtils interface {
	SMBMount(context.Context, string, string, string, string, string) error
	SMBUnmount(context.Context, string, string) error
	MakeDir(context.Context, string) error
	Rmdir(context.Context, string) error
	IsMountPointMatch(context.Context, mount.MountPoint, string) bool
	ExistsPath(context.Context, string) (bool, error)
	GetAPIVersions(ctx context.Context) string
	EvalHostSymlinks(context.Context, string) (string, error)
	GetFilesystemUsage(context.Context, string) (int64, int64, error)
}

type CertInfo

type CertInfo struct {
	CAKey      string
	CACert     string
	ServerKey  string
	ServerCert string
	ClientKey  string
	ClientCert string
}

func MakeHTTPCertInfo

func MakeHTTPCertInfo(caCertName, serverCertName, clientCertName string) (*CertInfo, error)

makeHTTPCertInfo generates a CA key and cert, then uses that key to sign two other keys and certs, one for a TLS server and one for a TLS client. None of the parameters are configurable...the serial numbers and principal names are hardcoded, the validity period is hardcoded to 1970-2070, and the algorithm and key size are hardcoded to 521-bit elliptic curve.

type DFInfo

type DFInfo struct {
	Target string
	Source string
}

DFInfo data structure for wrapping the parsed output from the 'df' command

func GetDFOutput

func GetDFOutput(ctx context.Context) ([]DFInfo, error)

GetDFOutput returns parsed DF output

type HTTPError

type HTTPError struct {
	Status     string
	StatusCode int
}

func NewHTTPError

func NewHTTPError(response *http.Response) *HTTPError

func (HTTPError) Error

func (e HTTPError) Error() string

type HostSystem

type HostSystem struct {
	OS       SystemOS `json:"os"`
	Services []string `json:"services,omitempty"`
}

func GetHostSystemInfo

func GetHostSystemInfo(ctx context.Context) (*HostSystem, error)

GetHostSystemInfo returns information about the host system

type ISCSIDiscoveryInfo

type ISCSIDiscoveryInfo struct {
	Portal     string
	PortalIP   string
	TargetName string
}

ISCSIDiscoveryInfo contains information about discovered iSCSI targets.

type ISCSISessionInfo

type ISCSISessionInfo struct {
	SID        string
	Portal     string
	PortalIP   string
	TargetName string
}

ISCSISessionInfo contains information about iSCSI sessions.

type IscsiAccessInfo

type IscsiAccessInfo struct {
	IscsiTargetPortal string   `json:"iscsiTargetPortal,omitempty"`
	IscsiPortals      []string `json:"iscsiPortals,omitempty"`
	IscsiTargetIQN    string   `json:"iscsiTargetIqn,omitempty"`
	IscsiLunNumber    int32    `json:"iscsiLunNumber,omitempty"`
	IscsiInterface    string   `json:"iscsiInterface,omitempty"`
	IscsiIgroup       string   `json:"iscsiIgroup,omitempty"`
	IscsiVAGs         []int64  `json:"iscsiVags,omitempty"`
	IscsiLunSerial    string   `json:"iscsiLunSerial,omitempty"`
	IscsiChapInfo
}

type IscsiChapInfo

type IscsiChapInfo struct {
	UseCHAP              bool   `json:"useCHAP"`
	IscsiUsername        string `json:"iscsiUsername,omitempty"`
	IscsiInitiatorSecret string `json:"iscsiInitiatorSecret,omitempty"`
	IscsiTargetUsername  string `json:"iscsiTargetUsername,omitempty"`
	IscsiTargetSecret    string `json:"iscsiTargetSecret,omitempty"`
}

func (IscsiChapInfo) String

func (i IscsiChapInfo) String() string

String implements the stringer interface and ensures that sensitive fields are redacted before being logged/printed

type LUKSDevice

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

func (*LUKSDevice) Close

func (d *LUKSDevice) Close(ctx context.Context) error

Close performs a luksClose on the LUKS device

func (*LUKSDevice) DevicePath

func (d *LUKSDevice) DevicePath() string

DevicePath returns the original device location, such as the iscsi device or multipath device. Ex: /dev/sdb

func (*LUKSDevice) IsLUKSFormatted

func (d *LUKSDevice) IsLUKSFormatted(ctx context.Context) (bool, error)

IsLUKSFormatted returns whether LUKS headers have been placed on the device

func (*LUKSDevice) IsOpen

func (d *LUKSDevice) IsOpen(ctx context.Context) (bool, error)

IsOpen returns whether the device is an active luks device on the host

func (*LUKSDevice) LUKSDeviceName

func (d *LUKSDevice) LUKSDeviceName() string

LUKSDeviceName returns the name of the LUKS device when opened

func (*LUKSDevice) LUKSDevicePath

func (d *LUKSDevice) LUKSDevicePath() string

LUKSDevicePath returns the location of the LUKS device when opened

func (*LUKSDevice) LUKSFormat

func (d *LUKSDevice) LUKSFormat(ctx context.Context, luksPassphrase string) error

LUKSFormat sets up LUKS headers on the device with the specified passphrase, this destroys data on the device

func (*LUKSDevice) Open

func (d *LUKSDevice) Open(ctx context.Context, luksPassphrase string) error

Open makes the device accessible on the host

type LUKSDeviceInterface

type LUKSDeviceInterface interface {
	DevicePath() string
	LUKSDevicePath() string
	LUKSDeviceName() string
	IsLUKSFormatted(ctx context.Context) (bool, error)
	IsOpen(ctx context.Context) (bool, error)
	LUKSFormat(ctx context.Context, luksPassphrase string) error
	Open(ctx context.Context, luksPassphrase string) error
}

type LoopDevice

type LoopDevice struct {
	Name string `json:"name"`
	// Sizelimit int64  `json:"sizelimit"`
	// Offset    int64  `json:"offset"`
	// Autoclear bool   `json:"autoclear"`
	// Ro        bool   `json:"ro"`
	BackFile string `json:"back-file"`
}

LoopDevice contains the details of a loopback device and is designed to be populated from the result of "losetup --list --json". Note that some fields changed from string to int/bool between Ubuntu 16.04 and 18.04, and likely other Linux distributions as well. The affected fields are unneeded here and are included but commented out for clarity.

func GetLoopDeviceAttachedToFile

func GetLoopDeviceAttachedToFile(ctx context.Context, loopFile string) (bool, *LoopDevice, error)

type LoopDevicesResponse

type LoopDevicesResponse struct {
	LoopDevices []LoopDevice `json:"loopdevices"`
}

type MountInfo

type MountInfo struct {
	MountId      int
	ParentId     int
	DeviceId     string
	Root         string
	MountPoint   string
	MountOptions []string
	// OptionalFields []string
	FsType       string
	MountSource  string
	SuperOptions []string
}

This represents a single line in /proc/self/mountinfo.

func GetHostMountInfo

func GetHostMountInfo(ctx context.Context) ([]MountInfo, error)

 GetHostMountInfo returns the list of mounts found in /proc/1/mountinfo

func GetSelfMountInfo

func GetSelfMountInfo(ctx context.Context) ([]MountInfo, error)

GetSelfMountInfo returns the list of mounts found in /proc/self/mountinfo

type MountPoint

type MountPoint struct {
	Device string
	Path   string
	Type   string
	Opts   []string
	Freq   int
	Pass   int
}

This represents a single line in /proc/mounts or /etc/fstab.

type NfsAccessInfo

type NfsAccessInfo struct {
	NfsServerIP string `json:"nfsServerIp,omitempty"`
	NfsPath     string `json:"nfsPath,omitempty"`
	NfsUniqueID string `json:"nfsUniqueID,omitempty"`
}

type NfsBlockAccessInfo

type NfsBlockAccessInfo struct {
	SubvolumeName         string `json:"subvolumeName,omitempty"`
	SubvolumeMountOptions string `json:"subvolumeMountOptions,omitempty"`
	NFSMountpoint         string `json:"nfsMountpoint,omitempty"`
}

type Node

type Node struct {
	Name           string            `json:"name"`
	IQN            string            `json:"iqn,omitempty"`
	IPs            []string          `json:"ips,omitempty"`
	TopologyLabels map[string]string `json:"topologyLabels,omitempty"`
	NodePrep       *NodePrep         `json:"nodePrep,omitempty"`
	HostInfo       *HostSystem       `json:"hostInfo,omitempty"`
	Deleted        bool              `json:"deleted"`
}

type NodePrep

type NodePrep struct {
	Enabled            bool           `json:"enabled"`
	NFS                NodePrepStatus `json:"nfs,omitempty"`
	NFSStatusMessage   string         `json:"nfsStatusMessage,omitempty"`
	ISCSI              NodePrepStatus `json:"iscsi,omitempty"`
	ISCSIStatusMessage string         `json:"iscsiStatusMessage,omitempty"`
}

NodePrep struct is deprecated and only here for backwards compatibility

type NodePrepBreadcrumb

type NodePrepBreadcrumb struct {
	TridentVersion string `json:"tridentVersion"`
	NFS            string `json:"nfs,omitempty"`
	ISCSI          string `json:"iscsi,omitempty"`
}

type NodePrepStatus

type NodePrepStatus string

type SMBAccessInfo

type SMBAccessInfo struct {
	SMBServer string `json:"smbServer,omitempty"`
	SMBPath   string `json:"smbPath,omitempty"`
}

type ScsiDeviceInfo

type ScsiDeviceInfo struct {
	Host            string
	Channel         string
	Target          string
	LUN             string
	Devices         []string
	MultipathDevice string
	Filesystem      string
	IQN             string
	HostSessionMap  map[int]int
}

ScsiDeviceInfo contains information about SCSI devices

func GetISCSIDevices

func GetISCSIDevices(ctx context.Context) ([]*ScsiDeviceInfo, error)

GetISCSIDevices returns a list of iSCSI devices that are attached to (but not necessarily mounted on) this host.

func GetMountedISCSIDevices

func GetMountedISCSIDevices(ctx context.Context) ([]*ScsiDeviceInfo, error)

GetMountedISCSIDevices returns a list of iSCSI devices that are *mounted* on this host.

type SystemOS

type SystemOS struct {
	Distro  string `json:"distro"` // ubuntu/centos/rhel/windows
	Version string `json:"version"`
	Release string `json:"release,omitempty"`
}

type Version

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

Version is an opaque representation of a version number

func MustParseDate

func MustParseDate(str string) *Version

MustParseDate is like ParseDate except that it panics on error

func MustParseGeneric

func MustParseGeneric(str string) *Version

MustParseGeneric is like ParseGeneric except that it panics on error

func MustParseMajorMinorVersion

func MustParseMajorMinorVersion(str string) *Version

MustParseMajorMinorVersion accepts a major-minor version and adds a dummy patch value to the version to satisfy the parser. There are circumstances where the caller is only concerned with the major-minor version

func MustParseSemantic

func MustParseSemantic(str string) *Version

MustParseSemantic is like ParseSemantic except that it panics on error

func ParseDate

func ParseDate(str string) (*Version, error)

ParseDate parses a version string that mostly obeys the syntax and semantics of the "Semantic Versioning" specification (http://semver.org/) (although it ignores leading and trailing whitespace, and allows the version to be preceded by "v"). Furthermore, it allows leading zeroes on the second numerical component so that the version may represent a two-digit month (i.e. 17.07.1). A date-based version string must be of the form <year>.<month>.<rev>[-preRelease][+buildMetadata], where the year/month/rev values are numerical, and the month must be in the range 1..12.

func ParseGeneric

func ParseGeneric(str string) (*Version, error)

ParseGeneric parses a "generic" version string. The version string must consist of two or more dot-separated numeric fields (the first of which can't have leading zeroes), followed by arbitrary uninterpreted data (which need not be separated from the final numeric field by punctuation). For convenience, leading and trailing whitespace is ignored, and the version can be preceded by the letter "v". See also ParseSemantic.

func ParseSemantic

func ParseSemantic(str string) (*Version, error)

ParseSemantic parses a version string that exactly obeys the syntax and semantics of the "Semantic Versioning" specification (http://semver.org/) (although it ignores leading and trailing whitespace, and allows the version to be preceded by "v"). For version strings that are not guaranteed to obey the Semantic Versioning syntax, use ParseGeneric.

func (*Version) AtLeast

func (v *Version) AtLeast(min *Version) bool

AtLeast tests if a version is at least equal to a given minimum version. If both Versions are Semantic Versions, this will use the Semantic Version comparison algorithm. Otherwise, it will compare only the numeric components, with non-present components being considered "0" (ie, "1.4" is equal to "1.4.0").

func (*Version) BuildMetadata

func (v *Version) BuildMetadata() string

BuildMetadata returns the build metadata, if v is a Semantic Version, or ""

func (*Version) Compare

func (v *Version) Compare(other string) (int, error)

Compare compares v against a version string (which will be parsed as either Semantic or non-Semantic depending on v). On success it returns -1 if v is less than other, 1 if it is greater than other, or 0 if they are equal.

func (*Version) GreaterThan

func (v *Version) GreaterThan(other *Version) bool

GreaterThan tests if a version is greater than a given version.

func (*Version) LessThan

func (v *Version) LessThan(other *Version) bool

LessThan tests if a version is less than a given version. (It is exactly the opposite of AtLeast, for situations where asking "is v too old?" makes more sense than asking "is v new enough?".)

func (*Version) MajorVersion

func (v *Version) MajorVersion() uint

func (*Version) MajorVersionString

func (v *Version) MajorVersionString() string

func (*Version) MinorVersion

func (v *Version) MinorVersion() uint

func (*Version) MinorVersionString

func (v *Version) MinorVersionString() string

func (*Version) PatchVersion

func (v *Version) PatchVersion() uint

func (*Version) PreRelease

func (v *Version) PreRelease() string

func (*Version) ShortString

func (v *Version) ShortString() string

ShortString converts a Version back to a string, including only the major/minor/patch components.

func (*Version) ShortStringWithRelease

func (v *Version) ShortStringWithRelease() string

ShortStringWithRelease converts a Version back to a string, including only the major/minor/patch components with release information

func (*Version) String

func (v *Version) String() string

String converts a Version back to a string; note that for versions parsed with ParseGeneric, this will not include the trailing uninterpreted portion of the version number.

func (*Version) ToMajorMinorString

func (v *Version) ToMajorMinorString() string

func (*Version) ToMajorMinorVersion

func (v *Version) ToMajorMinorVersion() *Version

type VolumeAccessInfo

type VolumeAccessInfo struct {
	IscsiAccessInfo
	NfsAccessInfo
	SMBAccessInfo
	NfsBlockAccessInfo
	MountOptions       string `json:"mountOptions,omitempty"`
	PublishEnforcement bool   `json:"publishEnforcement,omitempty"`
	ReadOnly           bool   `json:"readOnly,omitempty"`
	// The access mode values are defined by CSI
	// See https://github.com/container-storage-interface/spec/blob/release-1.5/lib/go/csi/csi.pb.go#L135
	AccessMode int32 `json:"accessMode,omitempty"`
}

type VolumePublication

type VolumePublication struct {
	Name       string `json:"name"`
	NodeName   string `json:"node"`
	VolumeName string `json:"volume"`
	ReadOnly   bool   `json:"readOnly"`
	// The access mode values are defined by CSI
	// See https://github.com/container-storage-interface/spec/blob/release-1.5/lib/go/csi/csi.pb.go#L135
	AccessMode      int32 `json:"accessMode"`
	NotSafeToAttach bool  `json:"notSafeToAttach"`
	Unpublished     bool  `json:"unpublished"` // Normally should not be set except during force detach scenarios
}

func (*VolumePublication) ConstructExternal

func (v *VolumePublication) ConstructExternal() *VolumePublicationExternal

type VolumePublicationExternal

type VolumePublicationExternal struct {
	Name       string `json:"name"`
	NodeName   string `json:"node"`
	VolumeName string `json:"volume"`
	ReadOnly   bool   `json:"readOnly"`
	// The access mode values are defined by CSI
	// See https://github.com/container-storage-interface/spec/blob/release-1.5/lib/go/csi/csi.pb.go#L135
	AccessMode      int32 `json:"accessMode"`
	NotSafeToAttach bool  `json:"notSafeToAttach"`
}

type VolumePublishInfo

type VolumePublishInfo struct {
	Localhost         bool     `json:"localhost,omitempty"`
	HostIQN           []string `json:"hostIQN,omitempty"`
	HostIP            []string `json:"hostIP,omitempty"`
	BackendUUID       string   `json:"backendUUID,omitempty"`
	Nodes             []*Node  `json:"nodes,omitempty"`
	HostName          string   `json:"hostName,omitempty"`
	FilesystemType    string   `json:"fstype,omitempty"`
	SharedTarget      bool     `json:"sharedTarget,omitempty"`
	DevicePath        string   `json:"devicePath,omitempty"`
	Unmanaged         bool     `json:"unmanaged,omitempty"`
	StagingMountpoint string   `json:"stagingMountpoint,omitempty"` // NOTE: Added in 22.04 release
	TridentUUID       string   `json:"tridentUUID,omitempty"`       // NOTE: Added in 22.07 release
	LUKSEncryption    string   `json:"LUKSEncryption,omitempty"`
	VolumeAccessInfo
}

type VolumeTrackingPublishInfo

type VolumeTrackingPublishInfo struct {
	StagingTargetPath string `json:"stagingTargetPath"`
}

Jump to

Keyboard shortcuts

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