mirror of
https://github.com/rancher/norman.git
synced 2025-06-24 14:31:42 +00:00
Some worload controllers need to watch resoruces in the mangement plane and react to them. But, they should only react to resources that correspond to their cluster. This adds framework support for that.
60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package controller
|
|
|
|
import (
|
|
"reflect"
|
|
"strings"
|
|
)
|
|
|
|
func ObjectInCluster(cluster string, obj interface{}) bool {
|
|
var clusterName string
|
|
if c := getValue(obj, "ClusterName"); c.IsValid() {
|
|
clusterName = c.String()
|
|
}
|
|
if clusterName == "" {
|
|
if c := getValue(obj, "Spec", "ClusterName"); c.IsValid() {
|
|
clusterName = c.String()
|
|
}
|
|
|
|
}
|
|
if clusterName == "" {
|
|
if c := getValue(obj, "ProjectName"); c.IsValid() {
|
|
if parts := strings.SplitN(c.String(), ":", 2); len(parts) == 2 {
|
|
clusterName = parts[0]
|
|
}
|
|
}
|
|
}
|
|
if clusterName == "" {
|
|
if c := getValue(obj, "Spec", "ProjectName"); c.IsValid() {
|
|
if parts := strings.SplitN(c.String(), ":", 2); len(parts) == 2 {
|
|
clusterName = parts[0]
|
|
}
|
|
}
|
|
}
|
|
|
|
return clusterName == cluster
|
|
}
|
|
|
|
func getValue(obj interface{}, name ...string) reflect.Value {
|
|
v := reflect.ValueOf(obj)
|
|
t := v.Type()
|
|
if t.Kind() == reflect.Ptr {
|
|
v = v.Elem()
|
|
t = v.Type()
|
|
}
|
|
|
|
field := v.FieldByName(name[0])
|
|
if !field.IsValid() || len(name) == 1 {
|
|
return field
|
|
}
|
|
|
|
return getFieldValue(field, name[1:]...)
|
|
}
|
|
|
|
func getFieldValue(v reflect.Value, name ...string) reflect.Value {
|
|
field := v.FieldByName(name[0])
|
|
if len(name) == 1 {
|
|
return field
|
|
}
|
|
return getFieldValue(field, name[1:]...)
|
|
}
|