sigs.k8s.io/cluster-api@v1.7.1/cmd/clusterctl/client/cluster/ownergraph.go (about)

     1  /*
     2  Copyright 2023 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 cluster
    18  
    19  import (
    20  	"context"
    21  	"strings"
    22  
    23  	"github.com/pkg/errors"
    24  	corev1 "k8s.io/api/core/v1"
    25  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    27  	"sigs.k8s.io/controller-runtime/pkg/client"
    28  
    29  	clusterctlv1 "sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3"
    30  )
    31  
    32  // OwnerGraph contains a graph with all the objects considered by clusterctl move as nodes and the OwnerReference relationship
    33  // between those objects as edges.
    34  type OwnerGraph map[string]OwnerGraphNode
    35  
    36  // OwnerGraphNode is a single node linking an ObjectReference to its OwnerReferences.
    37  type OwnerGraphNode struct {
    38  	Object corev1.ObjectReference
    39  	Owners []metav1.OwnerReference
    40  }
    41  
    42  // GetOwnerGraph returns a graph with all the objects considered by clusterctl move as nodes and the OwnerReference relationship between those objects as edges.
    43  // NOTE: this data structure is exposed to allow implementation of E2E tests verifying that CAPI can properly rebuild its
    44  // own owner references; there is no guarantee about the stability of this API. Using this test with providers may require
    45  // a custom implementation of this function, or the OwnerGraph it returns.
    46  func GetOwnerGraph(ctx context.Context, namespace, kubeconfigPath string) (OwnerGraph, error) {
    47  	p := newProxy(Kubeconfig{Path: kubeconfigPath, Context: ""})
    48  	invClient := newInventoryClient(p, nil)
    49  
    50  	graph := newObjectGraph(p, invClient)
    51  
    52  	// Gets all the types defined by the CRDs installed by clusterctl plus the ConfigMap/Secret core types.
    53  	err := graph.getDiscoveryTypes(ctx)
    54  	if err != nil {
    55  		return OwnerGraph{}, errors.Wrap(err, "failed to retrieve discovery types")
    56  	}
    57  
    58  	// graph.Discovery can not be used here as it will use the latest APIVersion for ownerReferences - not those
    59  	// present in the object `metadata.ownerReferences`.
    60  	owners, err := discoverOwnerGraph(ctx, namespace, graph)
    61  	if err != nil {
    62  		return OwnerGraph{}, errors.Wrap(err, "failed to discovery ownerGraph types")
    63  	}
    64  	return owners, nil
    65  }
    66  
    67  func discoverOwnerGraph(ctx context.Context, namespace string, o *objectGraph) (OwnerGraph, error) {
    68  	selectors := []client.ListOption{}
    69  	if namespace != "" {
    70  		selectors = append(selectors, client.InNamespace(namespace))
    71  	}
    72  	ownerGraph := OwnerGraph{}
    73  
    74  	discoveryBackoff := newReadBackoff()
    75  	for _, discoveryType := range o.types {
    76  		typeMeta := discoveryType.typeMeta
    77  		objList := new(unstructured.UnstructuredList)
    78  
    79  		if err := retryWithExponentialBackoff(ctx, discoveryBackoff, func(ctx context.Context) error {
    80  			return getObjList(ctx, o.proxy, typeMeta, selectors, objList)
    81  		}); err != nil {
    82  			return nil, err
    83  		}
    84  
    85  		// if we are discovering Secrets, also secrets from the providers namespace should be included.
    86  		if discoveryType.typeMeta.GetObjectKind().GroupVersionKind().GroupKind() == corev1.SchemeGroupVersion.WithKind("SecretList").GroupKind() {
    87  			providers, err := o.providerInventory.List(ctx)
    88  			if err != nil {
    89  				return nil, err
    90  			}
    91  			for _, p := range providers.Items {
    92  				if p.Type == string(clusterctlv1.InfrastructureProviderType) {
    93  					providerNamespaceSelector := []client.ListOption{client.InNamespace(p.Namespace)}
    94  					providerNamespaceSecretList := new(unstructured.UnstructuredList)
    95  					if err := retryWithExponentialBackoff(ctx, discoveryBackoff, func(ctx context.Context) error {
    96  						return getObjList(ctx, o.proxy, typeMeta, providerNamespaceSelector, providerNamespaceSecretList)
    97  					}); err != nil {
    98  						return nil, err
    99  					}
   100  					objList.Items = append(objList.Items, providerNamespaceSecretList.Items...)
   101  				}
   102  			}
   103  		}
   104  		for _, obj := range objList.Items {
   105  			// Exclude the kube-root-ca.crt ConfigMap from the owner graph.
   106  			if obj.GetKind() == "ConfigMap" && obj.GetName() == "kube-root-ca.crt" {
   107  				continue
   108  			}
   109  			// Exclude the default service account from the owner graph.
   110  			// This Secret is no longer generated by default in Kubernetes 1.24+.
   111  			// This is not a CAPI related Secret, so it can be ignored.
   112  			if obj.GetKind() == "Secret" && strings.Contains(obj.GetName(), "default-token") {
   113  				continue
   114  			}
   115  			ownerGraph = addNodeToOwnerGraph(ownerGraph, obj)
   116  		}
   117  	}
   118  	return ownerGraph, nil
   119  }
   120  
   121  func addNodeToOwnerGraph(graph OwnerGraph, obj unstructured.Unstructured) OwnerGraph {
   122  	// write code to add a node to the ownerGraph
   123  	graph[string(obj.GetUID())] = OwnerGraphNode{
   124  		Owners: obj.GetOwnerReferences(),
   125  		Object: corev1.ObjectReference{
   126  			APIVersion: obj.GetAPIVersion(),
   127  			Kind:       obj.GetKind(),
   128  			Name:       obj.GetName(),
   129  			Namespace:  obj.GetNamespace(),
   130  		},
   131  	}
   132  	return graph
   133  }