github.com/gocrane/crane@v0.11.0/pkg/recommendation/recommender/base/filter.go (about) 1 package base 2 3 import ( 4 "fmt" 5 "time" 6 7 analysisapi "github.com/gocrane/api/analysis/v1alpha1" 8 9 "github.com/gocrane/crane/pkg/recommendation/framework" 10 "github.com/gocrane/crane/pkg/utils" 11 ) 12 13 // Filter out k8s resources that are not supported by the recommender. 14 func (br *BaseRecommender) Filter(ctx *framework.RecommendationContext) error { 15 // 1. get object identity 16 identity := ctx.Identity 17 18 // 2. load recommender accepted kubernetes object 19 accepted := br.Recommender.AcceptedResourceSelectors 20 21 // 3. if not support, abort the recommendation flow 22 supported := IsIdentitySupported(identity, accepted) 23 if !supported { 24 return fmt.Errorf("recommender %s is failed at filter, your kubernetes resource is not supported for recommender %s ", br.Name(), br.Name()) 25 } 26 27 // 4. skip the objects that just created 28 creationCheckingTime := ctx.Object.GetCreationTimestamp().Add(br.CreationCoolDown) 29 if time.Now().Before(creationCheckingTime) { 30 return fmt.Errorf("recommender %s is failed at filter, Creation Cool Down %s ", br.Name(), ctx.Object.GetCreationTimestamp()) 31 } 32 33 // 5. skip the objects that deleting 34 if ctx.Object.GetDeletionTimestamp() != nil { 35 return fmt.Errorf("recommender %s is failed at filter, Is deleting ", br.Name()) 36 } 37 38 return nil 39 } 40 41 // IsIdentitySupported check whether object identity fit resource selector. 42 func IsIdentitySupported(identity framework.ObjectIdentity, selectors []analysisapi.ResourceSelector) bool { 43 for _, selector := range selectors { 44 if len(selector.Name) == 0 { 45 if selector.Kind == identity.Kind && selector.APIVersion == identity.APIVersion { 46 labelMatch, _ := utils.LabelSelectorMatched(identity.Labels, selector.LabelSelector) 47 if labelMatch { 48 return true 49 } 50 } 51 } else if selector.Kind == identity.Kind && selector.APIVersion == identity.APIVersion && selector.Name == identity.Name { 52 labelMatch, _ := utils.LabelSelectorMatched(identity.Labels, selector.LabelSelector) 53 if labelMatch { 54 return true 55 } 56 } 57 } 58 59 return false 60 }