utils

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2023 License: Apache-2.0 Imports: 55 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DiskAttachDetach ...
	DiskAttachDetach = "diskAttachDetach"
	// DiskProvision ...
	DiskProvision = "diskProvision"
	// DiskMount ...
	DiskMount = "diskMount"
	// DiskDelete ...
	DiskDelete = "diskDelete"
	// NasFilesystemCreate ...
	NasFilesystemCreate = "nasFilesystemCreate"
	// NasFilesystemDelete ...
	NasFilesystemDelete = "nasFilesystemDelete"
	// NasMountTargetCreate ...
	NasMountTargetCreate = "nasMountTargetCreate"
	// NasMountTargetDelete ...
	NasMountTargetDelete = "nasMountTargetDelete"
)
View Source
const (
	// UserAKID is user AK ID
	UserAKID = "/etc/.volumeak/akId"
	// UserAKSecret is user AK Secret
	UserAKSecret = "/etc/.volumeak/akSecret"
	// MetadataURL is metadata url
	MetadataURL = "http://100.100.100.200/latest/meta-data/"
	// RegionIDTag is region id
	RegionIDTag = "region-id"
	// InstanceIDTag is instance id
	InstanceIDTag = "instance-id"
	// DefaultRegion is default region
	DefaultRegion = "cn-hangzhou"
	// CsiPluginRunTimeFlagFile tag
	CsiPluginRunTimeFlagFile = "../alibabacloudcsiplugin.json"
	// RuncRunTimeTag tag
	RuncRunTimeTag = "runc"
	// RunvRunTimeTag tag
	RunvRunTimeTag = "runv"
	// ServiceType tag
	ServiceType = "SERVICE_TYPE"
	// PluginService represents the csi-plugin type.
	PluginService = "plugin"
	// ProvisionerService represents the csi-provisioner type.
	ProvisionerService = "provisioner"
	// InstallSnapshotCRD tag
	InstallSnapshotCRD = "INSTALL_SNAPSHOT_CRD"
	// MetadataMaxRetryCount ...
	MetadataMaxRetryCount = 4
	// VolDataFileName file
	VolDataFileName = "vol_data.json"

	// NsenterCmd is the nsenter command
	NsenterCmd = "nsenter --mount=/proc/1/ns/mnt --ipc=/proc/1/ns/ipc --net=/proc/1/ns/net --uts=/proc/1/ns/uts"

	// GiB ...
	GiB = 1024 * 1024 * 1024
)
View Source
const (
	// ConfigPath the secret mount file
	ConfigPath = "/var/addon/token-config"
)

Variables

View Source
var (
	// NodeAddrMap map for NodeID and its Address
	NodeAddrMap = map[string]string{}
	// NodeAddrMutex Mutex for NodeAddr map
	NodeAddrMutex sync.RWMutex
)
View Source
var DiskAttachDetachErrors = map[string]*errorInfo{
	"had volume node affinity conflict": {
		// contains filtered or unexported fields
	},
	"can't find disk:": {
		// contains filtered or unexported fields
	},
	"instance does not support this disk category.": {
		// contains filtered or unexported fields
	},
	"The specified disk is not a portable disk.": {
		// contains filtered or unexported fields
	},
}

DiskAttachDetachErrors are errors throwed by disk attach

View Source
var DiskDeleteErrors = map[string]*errorInfo{}

DiskDeleteErrors are errors throwed by disk delete

View Source
var DiskMountErrors = map[string]*errorInfo{}

DiskMountErrors are errors throwed by disk mount

View Source
var DiskProvisionErrors = map[string]*errorInfo{
	"disk size is not supported.": {
		// contains filtered or unexported fields
	},
	"The specified AZone inventory is insufficient": {
		// contains filtered or unexported fields
	},
}

DiskProvisionErrors are errors throwed by ecs create disk api

View Source
var KubeletRootDir = "/var/lib/kubelet"

KubeletRootDir kubelet root dir;

View Source
var KubernetesAlicloudIdentity = "Kubernetes.Alicloud/CsiPlugin"

KubernetesAlicloudIdentity set a identity label

View Source
var MountPathWithTLS = "/tls"

MountPathWithTLS tls mount path;

View Source
var NasFilesystemCreateErrors = map[string]*errorInfo{}

NasFilesystemCreateErrors are errors throwed by nas create

View Source
var NasFilesystemDeleteErrors = map[string]*errorInfo{}

NasFilesystemDeleteErrors are errors throwed by nas filesystem delete

View Source
var NasMountTargetCreateErrors = map[string]*errorInfo{}

NasMountTargetCreateErrors are errors throwed by nas mount target create

View Source
var NasMountTargetDeleteErrors = map[string]*errorInfo{}

NasMountTargetDeleteErrors are errors throwed by nas mount target delete

View Source
var NsenterArgs = []string{"--target=1", "--mount", "--ipc", "--net", "--uts", "--"}

Functions

func AppendJSONData added in v1.1.7

func AppendJSONData(dataFilePath string, appData map[string]string) error

AppendJSONData append map data to json file.

func Bytes2GiB added in v1.2.1

func Bytes2GiB(volumeSizeBytes int64) int64

BytesToGiB converts Bytes to GiB

func BytesToGiB added in v1.2.1

func BytesToGiB(volumeSizeBytes int64) int64

BytesToGiB converts Bytes to GiB

func CheckCmd added in v1.1.7

func CheckCmd(cmd string, name string) error

func CheckCmdArgs added in v1.1.7

func CheckCmdArgs(cmd string, args ...string) error

func CheckParameterValidate added in v1.1.5

func CheckParameterValidate(inputs []string) bool

CheckParameterValidate is check parameter validating in csi-plugin

func CheckQuotaPathValidate added in v1.1.5

func CheckQuotaPathValidate(kubeClient *kubernetes.Clientset, path string) error

CheckQuotaPathValidate is check quota path validating in csi-plugin

func CheckRequest added in v1.1.7

func CheckRequest(m map[string]string, path string) (bool, error)

func CheckRequestArgs added in v1.1.7

func CheckRequestArgs(m map[string]string) (bool, error)

CheckRequestArgs is check string is valid in args map

func CommandOnNode added in v1.2.1

func CommandOnNode(args ...string) *exec.Cmd

func ConnectorRun added in v1.1.7

func ConnectorRun(cmd string) (string, error)

ConnectorRun Run shell command with host connector host connector is daemon running in host.

func CreateCertPEM added in v1.1.5

func CreateCertPEM(option CertOption, ca *KeyPairArtifacts, begin, end time.Time, isClient bool) ([]byte, []byte, error)

CreateCertPEM function is create cacert pem

func CreateDest

func CreateDest(dest string) error

CreateDest create de destination dir

func CreateEvent added in v1.1.1

func CreateEvent(recorder record.EventRecorder, objectRef *v1.ObjectReference, eventType string, reason string, err string)

CreateEvent is create events

func Decrypt added in v1.0.5

func Decrypt(s string, keyring []byte) ([]byte, error)

Decrypt secret Decrypt

func DoMountInHost added in v1.1.7

func DoMountInHost(mntCmd string) error

func FindSuggestionByErrorMessage added in v1.1.0

func FindSuggestionByErrorMessage(errMsg, errorType string) string

FindSuggestionByErrorMessage get new error message by error type & error message

func FormatAndMount added in v1.1.7

func FormatAndMount(diskMounter *k8smount.SafeFormatAndMount, source string, target string, fstype string, mkfsOptions []string, mountOptions []string, omitFsCheck bool) error

formatAndMount uses unix utils to format and mount the given disk

func FormatNewDisk added in v1.2.0

func FormatNewDisk(readOnly bool, source, fstype, target string, mkfsOptions, mountOptions []string, diskMounter *k8smount.SafeFormatAndMount) error

func Fsync added in v1.1.5

func Fsync(f *os.File) error

Fsync is a wrapper around file.Sync(). Special handling is needed on darwin platform.

func GetAccessModes added in v1.2.1

func GetAccessModes(caps []*csi.VolumeCapability) *[]string

GetAccessModes returns a slice containing all of the access modes defined in the passed in VolumeCapabilities.

func GetDiskPtypePTtype added in v1.2.0

func GetDiskPtypePTtype(disk string) (fstype string, pttype string, err error)

GetDiskPtypePTtype uses 'blkid' to see if the given disk is unformatted

func GetFileContent added in v1.0.4

func GetFileContent(fileName string) string

GetFileContent get file content

func GetMetaData

func GetMetaData(resource string) (string, error)

GetMetaData get metadata from ecs meta-server

func GetMetrics added in v1.0.3

func GetMetrics(path string) (*csi.NodeGetVolumeStatsResponse, error)

GetMetrics get path metric

func GetNodeAddr added in v1.1.5

func GetNodeAddr(client kubernetes.Interface, node string, port string) (string, error)

GetNodeAddr get node address

func GetNodeIP added in v1.1.5

func GetNodeIP(client kubernetes.Interface, nodeID string) (net.IP, error)

GetNodeIP get node address

func GetNvmeDeviceByVolumeID added in v1.3.0

func GetNvmeDeviceByVolumeID(volumeID string) (device string, err error)

Get NVME device name by diskID; /dev/nvme0n1 0: means device index, 1: means namespace for nvme device; udevadm info --query=all --name=/dev/nvme0n1 | grep ID_SERIAL_SHORT | awk -F= '{print $2}' bp1bcfmvsobfauvxb3ow

func GetPodRunTime added in v1.0.4

func GetPodRunTime(req *csi.NodePublishVolumeRequest, clientSet *kubernetes.Clientset) (string, error)

GetPodRunTime Get Pod runtimeclass config Default as runc.

func GetPvNameFormPodMnt added in v1.1.5

func GetPvNameFormPodMnt(mntPath string) string

GetPvNameFormPodMnt get pv name

func GetRegionAndInstanceID added in v1.0.1

func GetRegionAndInstanceID() (string, string, error)

GetRegionAndInstanceID get region and instanceID object

func GetRegionID added in v1.3.0

func GetRegionID() (string, error)

GetRegionID Get RegionID from Environment Variables or Metadata

func GetRegionIDAndInstanceID added in v1.0.1

func GetRegionIDAndInstanceID(nodeName string) (string, string, error)

GetRegionIDAndInstanceID get regionID and instanceID object

func Gi2Bytes added in v1.1.7

func Gi2Bytes(gb int64) int64

func HasSpecificTagKey added in v1.1.7

func HasSpecificTagKey(tagKey string, disk *ecs.Disk) (bool, string)

func IsDir added in v1.0.2

func IsDir(path string) bool

IsDir check file is directory

func IsDirEmpty added in v1.0.1

func IsDirEmpty(name string) (bool, error)

IsDirEmpty return status of dir empty or not

func IsDirTmpfs added in v1.1.5

func IsDirTmpfs(path string) bool

IsDirTmpfs check path is tmpfs mounted or not

func IsFileExisting

func IsFileExisting(filename string) bool

IsFileExisting check file exist in volume driver or not

func IsHostFileExist added in v1.1.5

func IsHostFileExist(path string) bool

IsHostFileExist is check host file is existing in lvm

func IsKataInstall added in v1.1.7

func IsKataInstall() bool

IsKataInstall check kata daemon installed

func IsLikelyNotMountPoint added in v1.1.5

func IsLikelyNotMountPoint(file string) (bool, error)

IsLikelyNotMountPoint return status of mount point,this function fix IsMounted return 0 bug IsLikelyNotMountPoint determines if a directory is not a mountpoint. It is fast but not necessarily ALWAYS correct. If the path is in fact a bind mount from one part of a mount to another it will not be detected. It also can not distinguish between mountpoints and symbolic links. mkdir /tmp/a /tmp/b; mount --bind /tmp/a /tmp/b; IsLikelyNotMountPoint("/tmp/b") will return true. When in fact /tmp/b is a mount point. If this situation is of interest to you, don't use this function...

func IsMountPointRunv added in v1.0.4

func IsMountPointRunv(mountPoint string) bool

IsMountPointRunv check the mountpoint is runv style

func IsMounted

func IsMounted(mountPath string) bool

IsMounted return status of mount operation

func IsMountedInHost added in v1.1.7

func IsMountedInHost(mountPath string) bool

IsMountedInHost return status of host mounted or not

func IsPathAvailiable added in v1.1.7

func IsPathAvailiable(path string) error

IsPathAvailiable

func IsPrivateCloud added in v1.1.7

func IsPrivateCloud() bool

func KBlock2Bytes added in v1.2.0

func KBlock2Bytes(kblocks int64) int64

func LoadJSONData added in v1.1.7

func LoadJSONData(dataFileName string) (map[string]string, error)

LoadJSONData loads json info from specified json file

func NewClientTLSFromFile added in v1.1.5

func NewClientTLSFromFile(serverName, caFile, certFile, keyFile string) (credentials.TransportCredentials, error)

NewClientTLSFromFile function is new client with tls

func NewEcsClient added in v1.0.1

func NewEcsClient(ac AccessControl) (ecsClient *ecs.Client)

NewEcsClient create a ecsClient object

func NewEventRecorder added in v1.1.0

func NewEventRecorder() record.EventRecorder

NewEventRecorder is create snapshots event recorder

func NewServerTLSFromFile added in v1.1.5

func NewServerTLSFromFile(caFile, certFile, keyFile string) (credentials.TransportCredentials, error)

NewServerTLSFromFile function is new server with tls

func PKCS5UnPadding added in v1.0.5

func PKCS5UnPadding(origData []byte) []byte

PKCS5UnPadding get pkc

func Ping added in v1.1.1

func Ping(ipAddress string) (*ping.Statistics, error)

Ping check network like shell ping command

func ReadJSONFile added in v1.0.1

func ReadJSONFile(file string) (map[string]string, error)

ReadJSONFile return a json object

func RetryGetMetaData added in v1.1.5

func RetryGetMetaData(resource string) string

RetryGetMetaData ...

func RoundUpBytes added in v1.2.1

func RoundUpBytes(volumeSizeBytes int64) int64

RoundUpBytes rounds up the volume size in bytes upto multiplications of GiB in the unit of Bytes

func RoundUpGiB added in v1.2.1

func RoundUpGiB(volumeSizeBytes int64) int64

RoundUpGiB rounds up the volume size in bytes upto multiplications of GiB in the unit of GiB

func Run

func Run(cmd string) (string, error)

run shell command

func RunTimeout added in v1.1.4

func RunTimeout(cmd string, timeout int) error

RunTimeout tag

func RunWithFilter added in v1.1.7

func RunWithFilter(cmd string, filter ...string) ([]string, error)

func SetNodeAddrMap added in v1.1.7

func SetNodeAddrMap(key string, value string)

SetNodeAddrMap set map with mutex

func SetVolumeIOLimit added in v1.1.7

func SetVolumeIOLimit(devicePath string, req *csi.NodePublishVolumeRequest) error

SetVolumeIOLimit config io limit for device readIOPS: 1000 writeIOPS: 10000 readBPS: 100K writeBPS: 1M

func Umount

func Umount(mountPath string) error

Umount do an unmount operation

func UmountInHost added in v1.1.7

func UmountInHost(mountPath string) error

UmountInHost do an unmount operation

func ValidatePath added in v1.1.7

func ValidatePath(path string) (bool, error)

ValidatePath is check path string is valid

func ValidateRequest added in v1.1.7

func ValidateRequest(m map[string]string) (bool, error)

func ValidateRun added in v1.1.7

func ValidateRun(cmd string) (string, error)

Run command

func WriteAndSyncFile added in v1.1.5

func WriteAndSyncFile(filename string, data []byte, perm os.FileMode) error

WriteAndSyncFile behaves just like ioutil.WriteFile in the standard library, but calls Sync before closing the file. WriteAndSyncFile guarantees the data is synced if there is no error returned.

func WriteJSONFile added in v1.0.1

func WriteJSONFile(obj interface{}, file string) error

WriteJSONFile save json data to file

func WriteMetricsInfo added in v1.1.7

func WriteMetricsInfo(metricsPathPrefix string, req *csi.NodePublishVolumeRequest, metricsTop string, clientName string, storageBackendName string, fsName string)

Types

type AKInfo added in v1.0.5

type AKInfo struct {
	// AccessKeyId access key id
	AccessKeyID string `json:"access.key.id"`
	// AccessKeySecret access key secret
	AccessKeySecret string `json:"access.key.secret"`
	// SecurityToken security token
	SecurityToken string `json:"security.token"`
	// Expiration expiration duration
	Expiration string `json:"expiration"`
	// Keyring key ring
	Keyring string `json:"keyring"`
	// RoleAccessKeyId key
	RoleAccessKeyID string `json:"role.access.key.id"`
	// RoleAccessKeySecret key
	RoleAccessKeySecret string `json:"role.access.key.secret"`
	// RoleArn key
	RoleArn string `json:"role.arn"`
}

AKInfo access key info

type AccessControl added in v1.1.6

type AccessControl struct {
	AccessKeyID     string
	AccessKeySecret string
	StsToken        string
	RoleArn         string
	Config          *sdk.Config
	Credential      auth.Credential
	UseMode         AccessControlMode
}

AccessControl is access control option

func GetAccessControl added in v1.1.6

func GetAccessControl() AccessControl

GetAccessControl 1、Read default ak from local file. 2、If local default ak is not exist, then read from STS.

func GetDefaultRoleAK added in v1.1.5

func GetDefaultRoleAK() AccessControl

GetDefaultRoleAK 返回角色扮演账号AK, SK, role arn

func GetEnvAK added in v1.1.7

func GetEnvAK() AccessControl

GetEnvAK read ak from local ENV

type AccessControlMode added in v1.1.6

type AccessControlMode int

AccessControlMode is int, represents different modes

const (
	AccessKey AccessControlMode = iota
	ManagedToken
	EcsRAMRole
	Credential
	RoleArnToken
	OIDCToken
)

AccessControlMode includes AccessKey, ManagedToken, EcsRamRole, Credential, RoleArnToken, five types of access control

type CertOption added in v1.1.5

type CertOption struct {
	CAName          string
	CAOrganizations []string
	DNSNames        []string
	CommonName      string
}

CertOption is cert option

type CommandRunFunc added in v1.1.1

type CommandRunFunc func(cmd string) (string, error)

CommandRunFunc define the run function in utils for ut

type Config added in v1.3.0

type Config struct {
	ConfigMap map[string]string
}

func (*Config) Get added in v1.3.0

func (c *Config) Get(configKey, env, defaultValue string) string

func (*Config) GetBool added in v1.3.0

func (c *Config) GetBool(configKey, env string, defaultValue bool) bool

type DefaultOptions

type DefaultOptions struct {
	Global struct {
		KubernetesClusterTag string
		AccessKeyID          string `json:"accessKeyID"`
		AccessKeySecret      string `json:"accessKeySecret"`
		Region               string `json:"region"`
	}
}

DefaultOptions used for global ak

type KeyPairArtifacts added in v1.1.5

type KeyPairArtifacts struct {
	Cert    *x509.Certificate
	Key     *rsa.PrivateKey
	CertPEM []byte
	KeyPEM  []byte
}

KeyPairArtifacts is cert struct

func CreateCACert added in v1.1.5

func CreateCACert(option CertOption, begin, end time.Time) (*KeyPairArtifacts, error)

CreateCACert function is create cacert

type ManageTokens added in v1.1.5

type ManageTokens struct {
	// AccessKeyId key
	AccessKeyID string
	// AccessKeySecret key
	AccessKeySecret string
	// SecurityToken key
	SecurityToken string

	// RoleAccessKeyId key
	RoleAccessKeyID string
	// RoleAccessKeySecret key
	RoleAccessKeySecret string
	// RoleArn key
	RoleArn string
}

ManageTokens 定义资源账号 和 角色扮演账号

type MountPoint added in v1.1.7

type MountPoint struct {
	Device string
	Path   string
	Type   string
	Opts   []string // Opts may contain sensitive mount options (like passwords) and MUST be treated as such (e.g. not logged).
	Freq   int
	Pass   int
}

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

func ListProcMounts added in v1.1.7

func ListProcMounts() ([]MountPoint, error)

ListProcMounts is shared with NsEnterMounter

type Mounter added in v1.0.1

type Mounter interface {
	// If the folder doesn't exist, it will call 'mkdir -p'
	EnsureFolder(target string) error
	// If the block doesn't exist, create it
	EnsureBlock(target string) error
	// Format formats the source with the given filesystem type
	Format(source, fsType string) error

	// Mount mounts source to target with the given fstype and options.
	Mount(source, target, fsType string, options ...string) error

	// Mount mounts source to target for block file.
	MountBlock(source, target string, options ...string) error
	// Unmount unmounts the given target
	Unmount(target string) error

	// IsFormatted checks whether the source device is formatted or not. It
	// returns true if the source device is already formatted.
	IsFormatted(source string) (bool, error)

	// IsMounted checks whether the target path is a correct mount (i.e:
	// propagated). It returns true if it's mounted. An error is returned in
	// case of system errors or if it's mounted incorrectly.
	IsMounted(target string) (bool, error)

	IsNotMountPoint(file string) (bool, error)

	HasMountRefs(mountPath string, mountRefs []string) bool
}

Mounter is responsible for formatting and mounting volumes

func NewMounter added in v1.0.1

func NewMounter() Mounter

NewMounter returns a new mounter instance

type Result

type Result struct {
	Status  string `json:"status"`
	Message string `json:"message,omitempty"`
	Device  string `json:"device,omitempty"`
}

Result struct definition

func Fail

func Fail(a ...interface{}) Result

Fail return a Fail Result

func NotSupport

func NotSupport(a ...interface{}) Result

NotSupport return a NotSupport Result

func Succeed

func Succeed(a ...interface{}) Result

Succeed return a Succeed Result

type RoleAuth added in v1.0.1

type RoleAuth struct {
	AccessKeyID     string
	AccessKeySecret string
	Expiration      time.Time
	SecurityToken   string
	LastUpdated     time.Time
	Code            string
}

RoleAuth define STS Token Response

type VolumeLocks added in v1.3.0

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

func NewVolumeLocks added in v1.3.0

func NewVolumeLocks() *VolumeLocks

func (*VolumeLocks) Release added in v1.3.0

func (lock *VolumeLocks) Release(volumeID string)

Release releases lock in volume level

func (*VolumeLocks) TryAcquire added in v1.3.0

func (lock *VolumeLocks) TryAcquire(volumeID string) bool

TryAcquire tries to acquire the lock for operating on resourceID and returns true if successful. If another operation is already using resourceID, returns false.

Directories

Path Synopsis
kata

Jump to

Keyboard shortcuts

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