util

package
v0.7.2-beta.23 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2023 License: AGPL-3.0 Imports: 74 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ExposeToVPC      ExposeType = "vpc"
	ExposeToInternet ExposeType = "internet"

	EnableValue  string = "true"
	DisableValue string = "false"
)

Variables

View Source
var ProviderExposeAnnotations = map[K8sProvider]map[ExposeType]map[string]string{
	EKSProvider: {
		ExposeToVPC: 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: {
		ExposeToVPC: map[string]string{
			"networking.gke.io/load-balancer-type": "Internal",
		},
		ExposeToInternet: map[string]string{},
	},
	AKSProvider: {
		ExposeToVPC: 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: {
		ExposeToVPC: 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{},
	},
}

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 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 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 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 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 GetClusterNameFromArgsOrFlag added in v0.7.2

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

func GetComponentsFromClusterName

func GetComponentsFromClusterName(key client.ObjectKey, cli dynamic.Interface) ([]string, error)

GetComponentsFromClusterName returns name of component.

func GetComponentsFromResource

func GetComponentsFromResource(componentSpecs []appsv1alpha1.ClusterComponentSpec, clusterDefObj *appsv1alpha1.ClusterDefinition) ([]string, error)

GetComponentsFromResource returns name of component.

func GetConfigTemplateList

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

GetConfigTemplateList returns ConfigTemplate list used by the component.

func GetConfigTemplateListWithResource

func GetConfigTemplateListWithResource(cComponents []appsv1alpha1.ClusterComponentSpec,
	dComponents []appsv1alpha1.ClusterComponentDefinition,
	vComponents []appsv1alpha1.ClusterComponentVersion,
	componentName string,
	reloadTpl bool) ([]appsv1alpha1.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 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 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 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)

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

func GetKubeBlocksNamespace

func GetKubeBlocksNamespace(client kubernetes.Interface) (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 GetKubeconfigDir

func GetKubeconfigDir() string

GetKubeconfigDir returns the kubeconfig directory.

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 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 IsSupportReconfigureParams

func IsSupportReconfigureParams(tpl appsv1alpha1.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) *appsv1alpha1.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 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 *appsv1alpha1.ComponentConfigSpec, parameters sets.Set[string], cli dynamic.Interface) (err error)

func ValidateParametersModified2

func ValidateParametersModified2(parameters sets.Set[string], cc appsv1alpha1.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"
	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