util

package
v1.0.0-beta.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2024 License: AGPL-3.0 Imports: 78 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ExposeToIntranet ExposeType = "intranet"
	ExposeToInternet ExposeType = "internet"

	NodePort     string = "NodePort"
	LoadBalancer string = "LoadBalancer"

	EnableValue  string = "true"
	DisableValue string = "false"
)
View Source
const (
	// KubeblocksAppComponent the value of app.kubernetes.io/component label for KubeBlocks deployment
	KubeblocksAppComponent = "apps"
	// DataprotectionAppComponent the value of app.kubernetes.io/component label for DataProtection deployment
	DataprotectionAppComponent = "dataprotection"
)

Variables

View Source
var ProviderExposeAnnotations = map[K8sProvider]map[ExposeType]map[string]string{
	EKSProvider: {
		ExposeToIntranet: map[string]string{
			"service.beta.kubernetes.io/aws-load-balancer-type":     "nlb",
			"service.beta.kubernetes.io/aws-load-balancer-internal": "true",
		},
		ExposeToInternet: map[string]string{
			"service.beta.kubernetes.io/aws-load-balancer-type":     "nlb",
			"service.beta.kubernetes.io/aws-load-balancer-internal": "false",
		},
	},
	GKEProvider: {
		ExposeToIntranet: map[string]string{
			"networking.gke.io/load-balancer-type": "Internal",
		},
		ExposeToInternet: map[string]string{},
	},
	AKSProvider: {
		ExposeToIntranet: map[string]string{
			"service.beta.kubernetes.io/azure-load-balancer-internal": "true",
		},
		ExposeToInternet: map[string]string{
			"service.beta.kubernetes.io/azure-load-balancer-internal": "false",
		},
	},
	ACKProvider: {
		ExposeToIntranet: map[string]string{
			"service.beta.kubernetes.io/alibaba-cloud-loadbalancer-address-type": "intranet",
		},
		ExposeToInternet: map[string]string{
			"service.beta.kubernetes.io/alibaba-cloud-loadbalancer-address-type": "internet",
		},
	},

	TKEProvider: {
		ExposeToInternet: map[string]string{},
	},
	KINDProvider: {
		ExposeToIntranet: map[string]string{},
	},
	K3SProvider: {
		ExposeToIntranet: map[string]string{},
	},
	UnknownProvider: {
		ExposeToIntranet: map[string]string{},
		ExposeToInternet: map[string]string{},
	},
}

Functions

func AddDirToPath

func AddDirToPath(dir string) error

AddDirToPath add a dir to the PATH environment variable

func AddKlogFlags

func AddKlogFlags(fs *pflag.FlagSet)

AddKlogFlags adds flags from k8s.io/klog marks the flags as hidden to avoid showing them in help

func AppendErrIgnoreNotFound

func AppendErrIgnoreNotFound(allErrs *[]error, err error)

func BuildAddonReleaseName

func BuildAddonReleaseName(addon string) string

BuildAddonReleaseName returns the release name of addon, its f

func BuildClusterDefinitionRefLabel

func BuildClusterDefinitionRefLabel(prefix string, clusterDef []string) string

func BuildClusterLabel added in v0.7.3

func BuildClusterLabel(prefix string, addon []string) string

func BuildComponentNameLabels

func BuildComponentNameLabels(prefix string, names []string) string

func BuildLabelSelectorByNames

func BuildLabelSelectorByNames(selector string, names []string) string

BuildLabelSelectorByNames builds the label selector by instance names, the label selector is like "instance-key in (name1, name2)"

func BuildNodeAffinity

func BuildNodeAffinity(nodeLabels map[string]string) *corev1.NodeAffinity

BuildNodeAffinity build node affinity from node labels

func BuildPodAntiAffinity

func BuildPodAntiAffinity(podAntiAffinityStrategy string, topologyKeys []string) *corev1.PodAntiAffinity

BuildPodAntiAffinity build pod anti affinity from topology keys

func BuildPodAntiAffinityForComponent

func BuildPodAntiAffinityForComponent(tenancy string, clusterName string, compName string, podAntiAffinityStrategy string, topologyKeys []string) *corev1.PodAntiAffinity

BuildPodAntiAffinityForComponent build pod anti affinity from topology keys and tenancy for cluster

func BuildSchedulingPolicy

func BuildSchedulingPolicy(tenancy string, clusterName string, compName string, tolerations []corev1.Toleration, nodeLabels map[string]string, podAntiAffinity string, topologyKeys []string) (*kbappsv1.SchedulingPolicy, bool)

func BuildSemverVersion

func BuildSemverVersion(version string) string

BuildSemverVersion build semver version which starts with "v", such as "v1.0.0".

func BuildTolerations

func BuildTolerations(raw []string) ([]interface{}, error)

BuildTolerations toleration format: key=value:effect or key:effect,

func CheckEmpty

func CheckEmpty(str string) string

CheckEmpty checks if string is empty, if yes, returns <none> for displaying

func CheckErr

func CheckErr(err error)

CheckErr prints a user-friendly error to STDERR and exits with a non-zero exit code.

func CloneGitRepo

func CloneGitRepo(url, branch, path string) error

CloneGitRepo clones git repo to local path

func CloseQuietly

func CloseQuietly(d io.Closer)

CloseQuietly closes `io.Closer` quietly. Very handy and helpful for code quality too.

func CombineLabels

func CombineLabels(labels map[string]string) string

CombineLabels combines labels into a string

func CompGetFromTemplateWithLabels

func CompGetFromTemplateWithLabels(template *string, f cmdutil.Factory, namespace string, cmd *cobra.Command, args []string, labels []string, toComplete string) []string

CompGetFromTemplateWithLabels executes a Get operation using the specified template and args and returns the results which begin with `toComplete` and have the specified labels. example: CompGetFromTemplateWithLabels(&template, f, "", cmd, []string{"pods"}, []string{"app=nginx"}, toComplete) will get the output of `kubectl get pods --template=template -l app=nginx`, and split the output by space and return

func CompGetResourceWithLabels

func CompGetResourceWithLabels(f cmdutil.Factory, cmd *cobra.Command, resourceName string, labels []string, toComplete string) []string

CompGetResourceWithLabels gets the list of the resource specified which begin with `toComplete` and have the specified labels. example: CompGetResourceWithLabels(f, cmd, "pods", []string{"app=nginx"}, toComplete) gets the name of the pods which have the label `app=nginx` and begin with `toComplete`

func ComponentConfigSpecs

func ComponentConfigSpecs(clusterName string, namespace string, cli dynamic.Interface, componentName string, reloadTpl bool) ([]kbappsv1alpha1.ComponentConfigSpec, error)

ComponentConfigSpecs returns configSpecs used by the component.

func ConfigPath

func ConfigPath(name string) string

func ConvertObjToUnstructured

func ConvertObjToUnstructured(obj any) (*unstructured.Unstructured, error)

func CreateAndCleanFile

func CreateAndCleanFile(file string) (*os.File, error)

func CreateResourceIfAbsent

func CreateResourceIfAbsent(
	dynamic dynamic.Interface,
	gvr schema.GroupVersionResource,
	namespace string,
	unstructuredObj *unstructured.Unstructured) error

func DisplayDiffWithColor

func DisplayDiffWithColor(out io.Writer, diffText string)

func DoWithRetry

func DoWithRetry(ctx context.Context, logger logr.Logger, operation func() error, options *RetryOptions) error

func EnableLogToFile

func EnableLogToFile(fs *pflag.FlagSet) error

func EnsureCloned

func EnsureCloned(uri, destinationPath string) error

EnsureCloned clones into the destination path, otherwise returns no error.

func EnsureUpdated

func EnsureUpdated(uri, destinationPath string) error

EnsureUpdated ensures the destination path exists and is up to date.

func ExecGitCommand

func ExecGitCommand(pwd string, args ...string) (string, error)

ExecGitCommand executes a git command in the given directory.

func ExistMultiKubeBlocks

func ExistMultiKubeBlocks(client kubernetes.Interface) (bool, error)

func FileExists

func FileExists(fileName string) (bool, error)

FileExists check if a file exists, and return an error otherwise

func GVRToString

func GVRToString(gvr schema.GroupVersionResource) string

func GetCliAddonDir

func GetCliAddonDir() (string, error)

GetCliAddonDir returns kbcli addon index dir

func GetCliHomeDir

func GetCliHomeDir() (string, error)

GetCliHomeDir returns kbcli home dir

func GetCliLogDir

func GetCliLogDir() (string, error)

GetCliLogDir returns kbcli log dir

func GetClusterDefByName added in v0.9.0

func GetClusterDefByName(cli dynamic.Interface, clusterDefName string) (*kbappsv1alpha1.ClusterDefinition, error)

GetClusterDefByName gets the ClusterDefinition object by the name.

func GetClusterNameFromArgsOrFlag added in v0.7.2

func GetClusterNameFromArgsOrFlag(cmd *cobra.Command, args []string) string

func GetCompDefByName added in v0.9.0

func GetCompDefByName(cli dynamic.Interface, compDefName string) (*kbappsv1alpha1.ComponentDefinition, error)

GetCompDefByName gets the ComponentDefinition object by the name.

func GetComponentDefByCompName

func GetComponentDefByCompName(cli dynamic.Interface, clusterObj *kbappsv1.Cluster, compName string) (*kbappsv1.ComponentDefinition, error)

GetComponentDefByCompName gets the ComponentDefinition object by the component name.

func GetComponentDefByName

func GetComponentDefByName(dynamic dynamic.Interface, name string) (*kbappsv1.ComponentDefinition, error)

func GetComponentsFromResource

func GetComponentsFromResource(namespace, clusterName string, componentSpecs []kbappsv1.ClusterComponentSpec, cli dynamic.Interface) ([]string, error)

GetComponentsFromResource returns name of component.

func GetConfigSpecsFromComponentName added in v0.7.3

func GetConfigSpecsFromComponentName(cli dynamic.Interface, namespace, clusterName, componentName string, reloadTpl bool) ([]kbappsv1alpha1.ComponentConfigSpec, error)

func GetCurrentBranch added in v0.7.1

func GetCurrentBranch(destinationPath string) (string, error)

func GetDataProtectionDeploy

func GetDataProtectionDeploy(client kubernetes.Interface) (*appsv1.Deployment, error)

GetDataProtectionDeploy gets DataProtection deployments, now one kubernetes cluster only support one DataProtection

func GetDataProtectionDeploys

func GetDataProtectionDeploys(client kubernetes.Interface) ([]appsv1.Deployment, error)

func GetDefaultRoleSelector added in v0.9.0

func GetDefaultRoleSelector(cli dynamic.Interface,
	cluster *kbappsv1.Cluster,
	compDefName string,
	clusterCompDefRefName string) (string, error)

func GetDockerVersion

func GetDockerVersion() (*gv.Version, error)

GetDockerVersion get Docker Version

func GetEventObject

func GetEventObject(e *corev1.Event) string

func GetEventTimeStr

func GetEventTimeStr(e *corev1.Event) string

func GetExposeAnnotations

func GetExposeAnnotations(provider K8sProvider, exposeType ExposeType) (map[string]string, error)

func GetHelmChartRepoURL

func GetHelmChartRepoURL() string

GetHelmChartRepoURL gets helm chart repo, chooses one from GitHub and GitLab based on the IP location

func GetHumanReadableDuration

func GetHumanReadableDuration(startTime metav1.Time, endTime metav1.Time) string

GetHumanReadableDuration returns a succinct representation of the provided startTime and endTime with limited precision for consumption by humans.

func GetIPLocation

func GetIPLocation() (string, error)

func GetImageRegistryByProvider added in v0.9.0

func GetImageRegistryByProvider(client kubernetes.Interface) (string, error)

GetImageRegistryByProvider returns the image registry based on the k8s provider, for different providers, we will use different image registry.

Now, KubeBlocks has two image registries: docker.io and apecloud-registry.cn-zhangjiakou.cr.aliyuncs.com. KubeBlocks default image registry is apecloud-registry.cn-zhangjiakou.cr.aliyuncs.com, for some providers, or some regions, we should use docker.io as the image registry.

func GetK8SClientObject added in v0.7.2

func GetK8SClientObject(dynamic dynamic.Interface,
	obj client.Object,
	gvr schema.GroupVersionResource,
	namespace,
	name string) error

GetK8SClientObject gets the client object of k8s, obj must be a struct pointer so that obj can be updated with the response.

func GetK8sSemVer

func GetK8sSemVer(version string) string

func GetK8sVersion

func GetK8sVersion(discoveryClient discovery.DiscoveryInterface) (string, error)

GetK8sVersion gets k8s server version

func GetKBDeploys

func GetKBDeploys(client kubernetes.Interface, appName string, namespace string) ([]appsv1.Deployment, error)

GetKBDeploys gets KubeBlocks deployments, now one kubernetes cluster only support one KubeBlocks

func GetKubeBlocksCRDsURL added in v0.7.2

func GetKubeBlocksCRDsURL(kbVersion string) string

GetKubeBlocksCRDsURL gets the crds url by IP region.

func GetKubeBlocksDeploy

func GetKubeBlocksDeploy(client kubernetes.Interface) (*appsv1.Deployment, error)

func GetKubeBlocksDeploys

func GetKubeBlocksDeploys(client kubernetes.Interface) ([]appsv1.Deployment, error)

func GetKubeBlocksNamespace

func GetKubeBlocksNamespace(client kubernetes.Interface, specifiedNamespace string) (string, error)

GetKubeBlocksNamespace gets namespace of KubeBlocks installation, infer namespace from helm secrets

func GetKubeBlocksNamespaceByDynamic

func GetKubeBlocksNamespaceByDynamic(dynamic dynamic.Interface) (string, error)

GetKubeBlocksNamespaceByDynamic gets namespace of KubeBlocks installation, infer namespace from helm secrets

func GetKubeBlocksVersion

func GetKubeBlocksVersion(client kubernetes.Interface, namespace string) (string, error)

GetKubeBlocksVersion gets KubeBlocks version

func GetKubeconfigDir

func GetKubeconfigDir() string

GetKubeconfigDir returns the kubeconfig directory.

func GetMajorMinorVersion

func GetMajorMinorVersion(version string) string

func GetNodeByName

func GetNodeByName(nodes []*corev1.Node, name string) *corev1.Node

GetNodeByName chooses node by name from a node array

func GetPodStatus

func GetPodStatus(pods []corev1.Pod) (running, waiting, succeeded, failed int)

func GetPublicIP

func GetPublicIP() (string, error)

func GetResourceObjectFromGVR

func GetResourceObjectFromGVR(gvr schema.GroupVersionResource, key client.ObjectKey, client dynamic.Interface, k8sObj interface{}) error

GetResourceObjectFromGVR queries the resource object using GVR.

func GetUnifiedDiffString

func GetUnifiedDiffString(original, edited string, from, to string, contextLine int) (string, error)

func GetValidConfigSpecs

func GetValidConfigSpecs(reloadTpl bool, configSpecs []kbappsv1alpha1.ComponentConfigSpec) ([]kbappsv1alpha1.ComponentConfigSpec, error)

func GitGetRemoteURL

func GitGetRemoteURL(dir string) (string, error)

func IsGitCloned

func IsGitCloned(gitPath string) (bool, error)

IsGitCloned tests if the path is a git dir.

func IsRepoLatest

func IsRepoLatest(destinationPath string) (bool, error)

func IsSupportConfigFileReconfigure

func IsSupportConfigFileReconfigure(configTemplateSpec kbappsv1alpha1.ComponentConfigSpec, configFileKey string) bool

func IsSupportReconfigureParams

func IsSupportReconfigureParams(tpl kbappsv1alpha1.ComponentConfigSpec, values map[string]*string, cli dynamic.Interface) (bool, error)

IsSupportReconfigureParams checks whether all updated parameters belong to config template parameters.

func IsWindows

func IsWindows() bool

IsWindows returns true if the kbcli runtime situation is windows

func ListResourceByGVR

func ListResourceByGVR(ctx context.Context, client dynamic.Interface, namespace string, gvrs []schema.GroupVersionResource, selector []metav1.ListOptions, allErrs *[]error) []*unstructured.UnstructuredList

func MakeSSHKeyPair

func MakeSSHKeyPair(pubKeyPath, privateKeyPath string) error

MakeSSHKeyPair makes a pair of public and private keys for SSH access. Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file. Private Key generated is PEM encoded

func NewConfigFlagNoWarnings

func NewConfigFlagNoWarnings() *genericclioptions.ConfigFlags

NewConfigFlagNoWarnings returns a ConfigFlags that disables warnings.

func NewFactory

func NewFactory() cmdutil.Factory

func NewOpsRequestForReconfiguring

func NewOpsRequestForReconfiguring(opsName, namespace, clusterName string) *opsv1alpha1.OpsRequest

NewOpsRequestForReconfiguring returns a new common OpsRequest for Reconfiguring operation

func OpenBrowser

func OpenBrowser(url string) error

OpenBrowser opens browser with url in different OS system

func PrintGoTemplate

func PrintGoTemplate(wr io.Writer, tpl string, values interface{}) error

func PrintObjYAML

func PrintObjYAML(obj *unstructured.Unstructured) error

func RandRFC1123String

func RandRFC1123String(n int) string

RandRFC1123String generate a random string with length n, which fulfills RFC1123

func RegisterClusterCompletionFunc

func RegisterClusterCompletionFunc(cmd *cobra.Command, f cmdutil.Factory)

func RemoveConfig

func RemoveConfig(name string) error

func ResourceIsEmpty

func ResourceIsEmpty(res *resource.Quantity) bool

ResourceIsEmpty checks if resource is empty or not

func SetKubeConfig

func SetKubeConfig(cfg string) error

SetKubeConfig sets KUBECONFIG environment

func SortEventsByLastTimestamp

func SortEventsByLastTimestamp(events *corev1.EventList, eventType string) *[]apiruntime.Object

SortEventsByLastTimestamp sorts events by lastTimestamp

func TimeFormat

func TimeFormat(t *metav1.Time) string

func TimeFormatWithDuration

func TimeFormatWithDuration(t *metav1.Time, duration time.Duration) string

TimeFormatWithDuration formats time with specified precision

func TimeParse

func TimeParse(t string, precision time.Duration) (time.Time, error)

func TimeTimeFormat

func TimeTimeFormat(t time.Time) string

func TimeTimeFormatWithDuration

func TimeTimeFormatWithDuration(t time.Time, precision time.Duration) string

func ToV1ComponentConfigSpecs

func ToV1ComponentConfigSpecs(configSpecs []kbappsv1.ComponentConfigSpec) []kbappsv1alpha1.ComponentConfigSpec

func TrimVersionPrefix added in v0.7.2

func TrimVersionPrefix(version string) string

func UpdateAndCleanUntracked

func UpdateAndCleanUntracked(destinationPath string) error

UpdateAndCleanUntracked fetches origin and sets HEAD to origin/HEAD and also creates a pristine working directory by removing untracked files and directories.

func ValidateParametersModified

func ValidateParametersModified(tpl *kbappsv1alpha1.ComponentConfigSpec, parameters sets.Set[string], cli dynamic.Interface) (err error)

func ValidateParametersModified2

func ValidateParametersModified2(parameters sets.Set[string], cc kbappsv1beta1.ConfigConstraintSpec) error

func WritePogStreamingLog

func WritePogStreamingLog(ctx context.Context, client kubernetes.Interface, pod *corev1.Pod, logOptions corev1.PodLogOptions, writer io.Writer) error

Types

type ExposeType

type ExposeType string

type K8sProvider

type K8sProvider string
const (
	EKSProvider     K8sProvider = "EKS"
	GKEProvider     K8sProvider = "GKE"
	AKSProvider     K8sProvider = "AKS"
	ACKProvider     K8sProvider = "ACK"
	TKEProvider     K8sProvider = "TKE"
	KINDProvider    K8sProvider = "Kind"
	K3SProvider     K8sProvider = "K3S"
	UnknownProvider K8sProvider = "unknown"
)

func GetK8sProvider

func GetK8sProvider(version string, client kubernetes.Interface) (K8sProvider, error)

GetK8sProvider returns the k8s provider

func GetK8sProviderFromNodes

func GetK8sProviderFromNodes(nodes *corev1.NodeList) K8sProvider

GetK8sProviderFromNodes get k8s provider from node.spec.providerID

func GetK8sProviderFromVersion

func GetK8sProviderFromVersion(version string) K8sProvider

GetK8sProviderFromVersion gets k8s provider from field GitVersion in cluster server version

func (K8sProvider) IsCloud

func (p K8sProvider) IsCloud() bool

type RetryOptions

type RetryOptions struct {
	MaxRetry int
	Delay    time.Duration
}

type Version

type Version struct {
	KubeBlocks string
	Kubernetes string
	Cli        string
}

func GetVersionInfo

func GetVersionInfo(client kubernetes.Interface) (Version, error)

GetVersionInfo gets version include KubeBlocks, CLI and kubernetes

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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