k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/util/selector.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package util 18 19 import ( 20 "fmt" 21 "strings" 22 23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 24 ) 25 26 // ObjectSelector is an aggregation of namespace, labelSelector and fieldSelector. 27 type ObjectSelector struct { 28 Namespace string 29 LabelSelector string 30 FieldSelector string 31 } 32 33 // NewObjectSelector creates default object selector. 34 func NewObjectSelector() *ObjectSelector { 35 return &ObjectSelector{ 36 Namespace: metav1.NamespaceAll, 37 } 38 } 39 40 // Parse parses namespace, labelSelector and fieldSelector from params map. 41 func (o *ObjectSelector) Parse(params map[string]interface{}) error { 42 var err error 43 o.Namespace, err = GetStringOrDefault(params, "namespace", metav1.NamespaceAll) 44 if err != nil { 45 return err 46 } 47 o.LabelSelector, err = GetStringOrDefault(params, "labelSelector", "") 48 if err != nil { 49 return err 50 } 51 o.FieldSelector, err = GetStringOrDefault(params, "fieldSelector", "") 52 if err != nil { 53 return err 54 } 55 return nil 56 } 57 58 // String returns string representation of the selector. 59 func (o *ObjectSelector) String() string { 60 return CreateSelectorsString(o.Namespace, o.LabelSelector, o.FieldSelector) 61 } 62 63 // ApplySelectors sets label and field selectors in a given ListOptions object. 64 func (o *ObjectSelector) ApplySelectors(options *metav1.ListOptions) { 65 options.FieldSelector = o.FieldSelector 66 options.LabelSelector = o.LabelSelector 67 } 68 69 // CreateSelectorsString creates a string representation for given namespace, label selector and field selector. 70 func CreateSelectorsString(namespace, labelSelector, fieldSelector string) string { 71 var selectorsStrings []string 72 if namespace != metav1.NamespaceAll { 73 selectorsStrings = append(selectorsStrings, fmt.Sprintf("namespace(%s)", namespace)) 74 } 75 if labelSelector != "" { 76 selectorsStrings = append(selectorsStrings, fmt.Sprintf("labelSelector(%s)", labelSelector)) 77 } 78 if fieldSelector != "" { 79 selectorsStrings = append(selectorsStrings, fmt.Sprintf("fieldSelector(%s)", fieldSelector)) 80 } 81 if len(selectorsStrings) == 0 { 82 return "everything" 83 } 84 return fmt.Sprint(strings.Join(selectorsStrings, ", ")) 85 }