utils

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2024 License: Apache-2.0 Imports: 75 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// UserID is key of GitHub user ID in secret
	UserID = "user"
	// AccessToken is key of GitHub user password or personal token in secret
	AccessToken = "accessToken"
	// SSHKey is use to connect to the channel via SSH
	SSHKey = "sshKey"
	// Passphrase is used to open the SSH key
	Passphrase = "passphrase"
	// ClientKey is a client private key for connecting to a Git server
	ClientKey = "clientKey"
	// ClientCert is a client certificate for connecting to a Git server
	ClientCert = "clientCert"

	Error = " err: "
)
View Source
const (
	//MIDNIGHT define the midnight format
	MIDNIGHT = "12:00AM"
)
View Source
const NoiseLogLel = 5

NoiseLogLel - information inside "important functions"

View Source
const QuiteLogLel = 4

QuiteLogLel - "important" information

View Source
const VeryNoisy = 10

VeryNoisy = show call stack, routine and everything

Variables

View Source
var AppSubSummaryPredicateFunc = predicate.Funcs{
	UpdateFunc: func(e event.UpdateEvent) bool {
		klog.Info("UpdateFunc oldlabels:", e.ObjectOld.GetLabels())
		var clusterLabel string
		_, oldOK := e.ObjectOld.GetLabels()["apps.open-cluster-management.io/cluster"]
		clusterLabel, newOK := e.ObjectNew.GetLabels()["apps.open-cluster-management.io/cluster"]

		if !oldOK || !newOK || clusterLabel == "" {
			klog.V(1).Infof("Not a managed cluster appSubPackageStatus updated, old: %v/%v, new: %v/%v",
				e.ObjectOld.GetNamespace(), e.ObjectOld.GetName(), e.ObjectNew.GetNamespace(), e.ObjectNew.GetName())
			return false
		}

		oldAppSubSummary, ok := e.ObjectOld.(*appsubReportV1alpha1.SubscriptionReport)
		if !ok {
			klog.V(1).Infof("Not a valid managed cluster appSubPackageStatus, old: %v/%v", e.ObjectOld.GetNamespace(), e.ObjectOld.GetName())
			return false
		}

		newAppSubSummary, ok := e.ObjectNew.(*appsubReportV1alpha1.SubscriptionReport)
		if !ok {
			klog.V(1).Infof("Not a valid managed cluster appSubPackageStatus, new: %v/%v", e.ObjectNew.GetNamespace(), e.ObjectNew.GetName())
			return false
		}

		return !equality.Semantic.DeepEqual(oldAppSubSummary, newAppSubSummary)
	},
	CreateFunc: func(e event.CreateEvent) bool {
		klog.Info("CreateFunc oldlabels:", e.Object.GetLabels())

		var clusterLabel string
		clusterLabel, ok := e.Object.GetLabels()["apps.open-cluster-management.io/cluster"]

		if !ok || clusterLabel == "" {
			klog.V(1).Infof("Not a managed cluster appSubPackageStatus created: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
			return false
		}

		klog.V(1).Infof("New managed cluster appSubPackageStatus created: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
		return true
	},
	DeleteFunc: func(e event.DeleteEvent) bool {
		klog.Info("DeleteFunc oldlabels:", e.Object.GetLabels())

		var clusterLabel string
		clusterLabel, ok := e.Object.GetLabels()["apps.open-cluster-management.io/cluster"]
		if !ok || clusterLabel == "" {
			klog.V(1).Infof("Not a managed cluster appSubPackageStatus deleted: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
			return false
		}

		klog.Infof("managed cluster appSubPackageStatus deleted: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
		return true
	},
}
View Source
var ChannelPredicateFunctions = predicate.Funcs{
	UpdateFunc: func(e event.UpdateEvent) bool {
		newChn := e.ObjectNew.(*chnv1.Channel)
		oldChn := e.ObjectOld.(*chnv1.Channel)

		oldAnnotations := oldChn.GetAnnotations()
		newAnnotations := newChn.GetAnnotations()

		if !reflect.DeepEqual(oldAnnotations, newAnnotations) {
			return true
		}

		return !reflect.DeepEqual(newChn.Spec, oldChn.Spec)
	},
	CreateFunc: func(e event.CreateEvent) bool {
		return true
	},

	DeleteFunc: func(e event.DeleteEvent) bool {
		return true
	},
}

ChannelPredicateFunctions filters channel spec update

View Source
var ConfigMapKindStr = "ConfigMap"
View Source
var PlacementDecisionPredicateFunctions = predicate.Funcs{
	UpdateFunc: func(e event.UpdateEvent) bool {
		newPd, newOK := e.ObjectNew.(*clusterapi.PlacementDecision)
		oldPd, oldOK := e.ObjectOld.(*clusterapi.PlacementDecision)

		if !newOK || !oldOK {
			klog.Infof("not placementDecision object, skip....")
			return false
		}

		if !reflect.DeepEqual(newPd.Status.Decisions, oldPd.Status.Decisions) {
			klog.Infof("cluster Decision list updated old: %v, new:%v", oldPd.Status.Decisions, newPd.Status.Decisions)
			return true
		}

		return false
	},
	CreateFunc: func(e event.CreateEvent) bool {
		return true
	},

	DeleteFunc: func(e event.DeleteEvent) bool {
		return true
	},
}

PlacementDecisionPredicateFunctions filters PlacementDecision status decisions update

View Source
var SecretKindStr = "Secret"
View Source
var SercertReferredMarker = "IsReferredBySub-"

SercertReferredMarker is used as a label key to filter out the secert coming from reference

View Source
var ServiceAccountPredicateFunctions = predicate.Funcs{
	UpdateFunc: func(e event.UpdateEvent) bool {
		newSA := e.ObjectNew.(*corev1.ServiceAccount)

		if strings.EqualFold(newSA.Namespace, addonServiceAccountNamespace) && strings.EqualFold(newSA.Name, addonServiceAccountName) {
			klog.Infof("App Addon SA updated: %v/%v", addonServiceAccountNamespace, addonServiceAccountName)
			return true
		}

		return false
	},
	CreateFunc: func(e event.CreateEvent) bool {
		sa := e.Object.(*corev1.ServiceAccount)

		if strings.EqualFold(sa.Namespace, addonServiceAccountNamespace) && strings.EqualFold(sa.Name, addonServiceAccountName) {
			klog.Infof("App Addon SA created: %v/%v", addonServiceAccountNamespace, addonServiceAccountName)
			return true
		}

		return false
	},
	DeleteFunc: func(e event.DeleteEvent) bool {
		sa := e.Object.(*corev1.ServiceAccount)

		if strings.EqualFold(sa.Namespace, addonServiceAccountNamespace) && strings.EqualFold(sa.Name, addonServiceAccountName) {
			klog.Infof("App Addon SA deleted: %v/%v", addonServiceAccountNamespace, addonServiceAccountName)
			return true
		}

		return false
	},
}

ServiceAccountPredicateFunctions watches for App Addon SA changes

View Source
var SubscriptionGVK = schema.GroupVersionKind{
	Group:   appv1.SchemeGroupVersion.Group,
	Kind:    "Subscription",
	Version: appv1.SchemeGroupVersion.Version}
View Source
var SubscriptionPredicateFunctions = predicate.Funcs{
	UpdateFunc: func(e event.UpdateEvent) bool {
		subOld := e.ObjectOld.(*appv1.Subscription)
		subNew := e.ObjectNew.(*appv1.Subscription)

		return IsSubscriptionBasicChanged(subOld, subNew)
	},
}

SubscriptionPredicateFunctions filters status update

Functions

func AddPartOfLabel

func AddPartOfLabel(s *appv1.Subscription, m map[string]string) map[string]string

func AllowApplyTemplate

func AllowApplyTemplate(localClient client.Client, template *unstructured.Unstructured) bool

AllowApplyTemplate check if the template is allowed to apply based on its hosting subscription pause label return false if the hosting subscription is paused.

func Base64StringDecode added in v0.5.0

func Base64StringDecode(encodedStr string) string

func CheckPackageOverride

func CheckPackageOverride(ov *appv1.Overrides) error

func CloneGitRepo

func CloneGitRepo(cloneOptions *GitCloneOption) (commitID string, err error)

CloneGitRepo clones a GitHub repository

func CompareManifestWork added in v0.5.0

func CompareManifestWork(oldManifestWork, newManifestWork *manifestWorkV1.ManifestWork) bool

CompareManifestWork compare two manifestWorks and return true if they are equal.

func ConvertLabels

func ConvertLabels(labelSelector *metav1.LabelSelector) (labels.Selector, error)

ConvertLabels coverts label selector to lables.Selector

func CreateClusterManagementAddon added in v0.7.0

func CreateClusterManagementAddon(clt client.Client)

func CreateFailedAppsubReportResult added in v0.5.0

func CreateFailedAppsubReportResult(client client.Client, cluster string, appsubNs, appsubName, statusMsg string) error

Create PropagatioFailed result in cluster appsubReport in the managed cluster namespace

func CreateHelmCRManifest added in v0.5.0

func CreateHelmCRManifest(
	repoURL string,
	packageName string,
	chartVersions repo.ChartVersions,
	client client.Client,
	channel *chnv1.Channel,
	secondaryChannel *chnv1.Channel,
	sub *appv1.Subscription,
	clusterAdmin bool) (*unstructured.Unstructured, error)

func CreateOrUpdateHelmChart

func CreateOrUpdateHelmChart(
	packageName string,
	releaseCRName string,
	chartVersions repo.ChartVersions,
	client client.Client,
	channel *chnv1.Channel,
	secondaryChannel *chnv1.Channel,
	sub *appv1.Subscription) (helmRelease *releasev1.HelmRelease, err error)

func DeleteHelmReleaseCRD

func DeleteHelmReleaseCRD(runtimeClient client.Client, crdx *clientsetx.Clientset)

DeleteHelmReleaseCRD deletes the HelmRelease CRD

func DeleteReferredObjects added in v0.5.0

func DeleteReferredObjects(clt client.Client, rq types.NamespacedName, gvk schema.GroupVersionKind) error

func DeleteSubscriptionCRD

func DeleteSubscriptionCRD(runtimeClient client.Client, crdx *clientsetx.Clientset)

DeleteSubscriptionCRD deletes the Subscription CRD

func DetectPlacementDecision added in v0.6.0

func DetectPlacementDecision(ctx context.Context, clReader client.Reader, clt client.Client)

DetectPlacementDecision - Detect the Placement Decision API every 10 seconds. the controller will be exited when it is ready The controller will be auto restarted by the multicluster-operators-application deployment CR later.

func EnterFnString

func EnterFnString() string

EnterFnString - called when enter a function

func ExitFuString

func ExitFuString(s string)

ExitFuString - called when exiting a function

func FetchChannelReferences added in v0.5.0

func FetchChannelReferences(clt client.Client, chn chnv1.Channel) (sec *corev1.Secret, cm *corev1.ConfigMap)

FetchChannelReferences best-effort to return the channel secret and configmap if they exist

func FilterCharts

func FilterCharts(sub *appv1.Subscription, indexFile *repo.IndexFile) error

FilterCharts filters the indexFile by name, version, digest

func FilterOutTimeRelatedFields

func FilterOutTimeRelatedFields(in *appv1.Subscription) *appv1.Subscription

the input object shouldn't be changed at all

func GenerateHelmIndexFile

func GenerateHelmIndexFile(sub *appv1.Subscription, repoRoot string, chartDirs map[string]string) (*repo.IndexFile, error)

GenerateHelmIndexFile generate helm repo index file

func GenerateServerCerts

func GenerateServerCerts(dir string) error

func GetAllowDenyLists added in v0.5.0

func GetAllowDenyLists(subscription appv1.Subscription) (map[string]map[string]string, map[string]map[string]string)

GetAllowDenyLists returns subscription's allow and deny lists as maps. It returns empty map if there is no list.

func GetChannelConfigMap

func GetChannelConfigMap(client client.Client, chn *chnv1.Channel) *corev1.ConfigMap

GetDataFromChannelConfigMap returns username and password for channel

func GetChannelSecret

func GetChannelSecret(client client.Client, chn *chnv1.Channel) (string, string, []byte, []byte, []byte, []byte, error)

GetChannelSecret returns username and password for channel

func GetCheckSum added in v0.9.0

func GetCheckSum(kubeconfigfile string) ([32]byte, error)

GetCheckSum generates a checksum of a kube config file

func GetClientConfigFromKubeConfig added in v0.7.0

func GetClientConfigFromKubeConfig(kubeconfigFile string) (*rest.Config, error)

func GetComponentNamespace

func GetComponentNamespace() string

func GetFnName

func GetFnName() string

GetFnName - get name of function

func GetHostSubscriptionFromObject

func GetHostSubscriptionFromObject(obj metav1.Object) *types.NamespacedName

GetHostSubscriptionFromObject extract the namespacedname of subscription hosting the object resource

func GetKubeIgnore

func GetKubeIgnore(resourcePath string) *gitignore.GitIgnore

GetKubeIgnore get .kubernetesignore list

func GetLatestCommitID

func GetLatestCommitID(url, branch string, clt ...*github.Client) (string, error)

func GetLocalGitFolder

func GetLocalGitFolder(sub *appv1.Subscription) string

GetLocalGitFolder returns the local Git repo clone directory

func GetPackageAlias

func GetPackageAlias(sub *appv1.Subscription, packageName string) string

func GetPauseLabel

func GetPauseLabel(instance *appv1.Subscription) bool

GetPauseLabel check if the subscription-pause label exists

func GetReconcileInterval

func GetReconcileInterval(reconcileRate, chType string) (time.Duration, time.Duration, int)

GetReconcileInterval determines reconcile loop interval based on reconcileRate setting

func GetReconcileRate

func GetReconcileRate(chnAnnotations, subAnnotations map[string]string) string

GetReconcileRate determines reconcile rate based on channel annotations

func GetReleaseName

func GetReleaseName(base string) (string, error)

GetReleaseName alters the given name in a deterministic way if the length exceed the maximum character

func GetSubscriptionBranch

func GetSubscriptionBranch(sub *appv1.Subscription) plumbing.ReferenceName

GetSubscriptionBranch returns GitHub repo branch for a given subscription

func GetSubscriptionBranchRef

func GetSubscriptionBranchRef(b string) plumbing.ReferenceName

func GetTestGitRepoURLFromEnvVar added in v0.5.0

func GetTestGitRepoURLFromEnvVar() string

func IsClusterAdmin

func IsClusterAdmin(client client.Client, sub *appv1.Subscription, eventRecorder *EventRecorder) bool

func IsEqualSubScriptionStatus

func IsEqualSubScriptionStatus(o, n *appv1.SubscriptionStatus) bool

func IsGitChannel

func IsGitChannel(chType string) bool

IsGitChannel returns true if channel type is github or git

func IsHostingAppsub added in v0.5.0

func IsHostingAppsub(appsub *appv1.Subscription) bool

IsHostingAppsub return true if contains hosting annotation

func IsHub

func IsHub(config *rest.Config) bool

IsHub determines the hub cluster by listing multiclusterhubs resource items

func IsHubRelatedStatusChanged

func IsHubRelatedStatusChanged(old, nnew *appv1.SubscriptionStatus) bool

func IsInWindow

func IsInWindow(tw *appv1alpha1.TimeWindow, t time.Time) bool

IsInWindow returns true if the give time is within a timewindow

func IsReadyManagedClusterView added in v0.7.0

func IsReadyManagedClusterView(clReader client.Reader) bool

IsReadyManagedClusterView check if managed cluster view API is ready or not.

func IsReadyPlacementDecision added in v0.6.0

func IsReadyPlacementDecision(clReader client.Reader) bool

IsReadyPlacementDecision check if Placement Decision API is ready or not.

func IsReadySubscription added in v0.11.0

func IsReadySubscription(clReader client.Reader, hub bool) bool

IsReadySubscription check if Subscription API is ready or not.

func IsResourceAllowed added in v0.5.0

func IsResourceAllowed(resource unstructured.Unstructured, allowlist map[string]map[string]string, isAdmin bool) bool

IsResourceAllowed checks if the resource is on application subscription's allow list. The allow list is used only if the subscription is created by subscription-admin user.

func IsResourceDenied added in v0.5.0

func IsResourceDenied(resource unstructured.Unstructured, denyList map[string]map[string]string, isAdmin bool) bool

IsResourceDenied checks if the resource is on application subscription's deny list. The deny list is used only if the subscription is created by subscription-admin user.

func IsSubscriptionBasicChanged

func IsSubscriptionBasicChanged(o, n *appv1.Subscription) bool

func IsSubscriptionBeDeleted

func IsSubscriptionBeDeleted(clt client.Client, subKey types.NamespacedName) bool

func IsSubscriptionResourceChanged

func IsSubscriptionResourceChanged(oSub, nSub *appv1.Subscription) bool

func IsURL

func IsURL(str string) bool

IsURL return true if string is a valid URL

func KeywordsChecker

func KeywordsChecker(labelSelector *metav1.LabelSelector, ks []string) bool

KeywordsChecker Checks if the helm chart has at least 1 keyword from the packageFilter.Keywords array

func KubeResourceParser

func KubeResourceParser(file []byte, cond Kube) [][]byte

func LabelChecker

func LabelChecker(ls *metav1.LabelSelector, dplls map[string]string) bool

func LabelsChecker

func LabelsChecker(labelSelector *metav1.LabelSelector, ls map[string]string) bool

LabelsChecker checks labels against a labelSelector

func ListAndDeployReferredObject added in v0.5.0

func ListAndDeployReferredObject(clt client.Client, instance *appv1.Subscription, gvk schema.GroupVersionKind, refObj referredObject) error

ListAndDeployReferredObject handles the create/update reconciler request the idea is, first it will try to get the referred secret from the subscription namespace if it can't find it, //it could be it's a brand new secret request or it's trying to use a differenet one. // to address these, we will try to list the sercert within the subscription namespace with the subscription label. // if we are seeing these secret, we will delete the label of the reconciled subscription. /// then we will create a new secret and label it if we can find a secret at the subscription namespace, it means there must be some other subscription is using it. In this case, we will just add an extra label to it

func MatchLabelForSubAndDpl

func MatchLabelForSubAndDpl(ls *metav1.LabelSelector, dplls map[string]string) bool

func NamespacedNameFormat

func NamespacedNameFormat(str string) types.NamespacedName

func NextStartPoint

func NextStartPoint(tw *appv1alpha1.TimeWindow, t time.Time) time.Duration

NextStartPoint will map the container's time to the location time specified by user then it will handle the window type as will the hour ange and daysofweek for hour range and daysofweek, it will handle as the following if hour range is empty and weekday is empty then retrun 0 if hour range is empty and weekday is not then return nextday durtion(here the window type will be considered again)

func NextStatusReconcile

func NextStatusReconcile(tw *appv1alpha1.TimeWindow, t time.Time) time.Duration

NextStatusReconcile generate a duartion for the reconcile to requeue after

func Override

func Override(helmRelease *releasev1.HelmRelease, sub *appv1.Subscription) error

func OverrideKustomize

func OverrideKustomize(pov appv1.PackageOverride, kustomizeDir string) error

func OverrideResourceBySubscription

func OverrideResourceBySubscription(template *unstructured.Unstructured,
	pkgName string, instance *appv1.Subscription) (*unstructured.Unstructured, error)

OverrideResourceBySubscription alter the given template with overrides

func OverrideTemplate

func OverrideTemplate(template *unstructured.Unstructured, overrides []appsubv1.ClusterOverride) (*unstructured.Unstructured, error)

OverrideTemplate alter the given template with overrides.

func ParseAPIVersion added in v0.5.0

func ParseAPIVersion(apiVersion string) (string, string)

ParseAPIVersion return group and version from a given apiVersion string

func ParseChannelSecret

func ParseChannelSecret(secret *corev1.Secret) (string, string, []byte, []byte, []byte, []byte, error)

func ParseKubeResoures

func ParseKubeResoures(file []byte) [][]byte

ParseKubeResoures parses a YAML content and returns kube resources in byte array from the file

func ParseNamespacedName added in v0.5.0

func ParseNamespacedName(namespacedName string) (string, string)

ParseNamespacedName return namespace and name from a given "namespace/name" string

func ParseYAML

func ParseYAML(fileContent []byte) []string

func PkgToReleaseCRName

func PkgToReleaseCRName(sub *appv1.Subscription, packageName string) (string, error)

func PrepareOverrides

func PrepareOverrides(cluster types.NamespacedName, appsub *appsubv1.Subscription) ([]appsubv1.ClusterOverride, error)

PrepareOverrides returns the overridemap for given subscription instance.

func RemoveSubAnnotations

func RemoveSubAnnotations(obj *unstructured.Unstructured) *unstructured.Unstructured

RemoveSubAnnotations removes RHACM specific annotations from subscription

func RemoveSubOwnerRef

func RemoveSubOwnerRef(obj *unstructured.Unstructured) *unstructured.Unstructured

RemoveSubOwnerRef removes RHACM specific owner reference from subscription

func RunKustomizeBuild

func RunKustomizeBuild(kustomizeDir string) ([]byte, error)

RunKustomizeBuild runs kustomize build and returns the build output

func SetInClusterPackageStatus

func SetInClusterPackageStatus(substatus *appv1.SubscriptionStatus, pkgname string, pkgerr error, status interface{}) error

SetInClusterPackageStatus creates status strcuture and fill status

func SetPartOfLabel

func SetPartOfLabel(s *appv1.Subscription, rsc *unstructured.Unstructured)

func SkipHooksOnManaged

func SkipHooksOnManaged(resourcePath, curPath string) bool

func SortResources

func SortResources(repoRoot, resourcePath string, skips ...SkipFunc) (map[string]string, map[string]string, []string, []string, []string, error)

SortResources sorts kube resources into different arrays for processing them later.

func UnifyTimeZone

func UnifyTimeZone(tw *appv1alpha1.TimeWindow, t time.Time) time.Time

UnifyTimeZone convert a given time to the timewindow time zone, if the time window doesn't sepcifiy a time zone, then the running machine's time zone will be used

func UpdateLastUpdateTime added in v0.7.0

func UpdateLastUpdateTime(clt client.Client, instance *appv1.Subscription)

func UpdateSubscriptionStatus

func UpdateSubscriptionStatus(clt client.Client, subName, subNs string, phase appv1.SubscriptionPhase, reason string)

func ValidateK8sLabel

func ValidateK8sLabel(s string) string

ValidateK8sLabel returns a valid k8s label string by enforcing k8s label values rules as below

  1. Must consist of alphanumeric characters, '-', '_' or '.' No need to check this as the input string is the host name of the k8s api url
  2. Must be no more than 63 characters
  3. Must start and end with an alphanumeric character

func VerifyAndOverrideKustomize

func VerifyAndOverrideKustomize(packageOverrides []*appv1.Overrides, relativePath, kustomizeDir string) error

Types

type ChannelConnectionCfg added in v0.5.0

type ChannelConnectionCfg struct {
	RepoURL            string
	User               string
	Password           string
	SSHKey             []byte
	Passphrase         []byte
	InsecureSkipVerify bool
	CaCerts            string
	ClientKey          []byte
	ClientCert         []byte
}

type EventRecorder

type EventRecorder struct {
	record.EventRecorder
}

EventRecorder - record kubernetes event

func NewEventRecorder

func NewEventRecorder(cfg *rest.Config, scheme *apiruntime.Scheme) (*EventRecorder, error)

NewEventRecorder - create new event recorder from rect config

func (*EventRecorder) RecordEvent

func (rec *EventRecorder) RecordEvent(obj apiruntime.Object, reason, msg string, err error)

RecordEvent - record kuberentes event

type GitCloneOption

type GitCloneOption struct {
	CommitHash                string
	RevisionTag               string
	Branch                    plumbing.ReferenceName
	DestDir                   string
	CloneDepth                int
	PrimaryConnectionOption   *ChannelConnectionCfg
	SecondaryConnectionOption *ChannelConnectionCfg
}

type Kube

type Kube func(KubeResource) bool

type KubeResource

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

KKubeResource export the kuKubeResource for other package

type SkipFunc

type SkipFunc func(string, string) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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