Skip to content

Commit

Permalink
ClusterToObjectsMapper: use namespace in client.List
Browse files Browse the repository at this point in the history
Signed-off-by: Stefan Büringer buringerst@vmware.com
  • Loading branch information
sbueringer committed Oct 6, 2021
1 parent 18ecf48 commit 9d132ea
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -489,15 +490,30 @@ func ClusterToObjectsMapper(c client.Client, ro client.ObjectList, scheme *runti
return nil, err
}

isNamespaced, err := isAPINamespaced(gvk, c.RESTMapper())
if err != nil {
return nil, err
}

return func(o client.Object) []ctrl.Request {
cluster, ok := o.(*clusterv1.Cluster)
if !ok {
return nil
}

listOpts := []client.ListOption{
client.MatchingLabels{
clusterv1.ClusterLabelName: cluster.Name,
},
}

if isNamespaced {
listOpts = append(listOpts, client.InNamespace(cluster.Namespace))
}

list := &unstructured.UnstructuredList{}
list.SetGroupVersionKind(gvk)
if err := c.List(context.TODO(), list, client.MatchingLabels{clusterv1.ClusterLabelName: cluster.Name}); err != nil {
if err := c.List(context.TODO(), list, listOpts...); err != nil {
return nil
}

Expand All @@ -511,6 +527,25 @@ func ClusterToObjectsMapper(c client.Client, ro client.ObjectList, scheme *runti
}, nil
}

// isAPINamespaced detects if a GroupVersionKind is namespaced.
func isAPINamespaced(gk schema.GroupVersionKind, restmapper meta.RESTMapper) (bool, error) {
restmapping, err := restmapper.RESTMapping(schema.GroupKind{Group: gk.Group, Kind: gk.Kind})
if err != nil {
return false, fmt.Errorf("failed to get restmapping: %w", err)
}

scope := restmapping.Scope.Name()

switch {
case scope == "":
return false, errors.New("Scope cannot be identified. Empty scope returned")
case scope != meta.RESTScopeNameRoot:
return true, nil
default:
return false, nil
}
}

// ObjectReferenceToUnstructured converts an object reference to an unstructured object.
func ObjectReferenceToUnstructured(in corev1.ObjectReference) *unstructured.Unstructured {
out := &unstructured.Unstructured{}
Expand Down

0 comments on commit 9d132ea

Please sign in to comment.