sigs.k8s.io/cluster-api@v1.7.1/api/v1beta1/index/cluster.go (about)

     1  /*
     2  Copyright 2021 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 index
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	"github.com/pkg/errors"
    24  	ctrl "sigs.k8s.io/controller-runtime"
    25  	"sigs.k8s.io/controller-runtime/pkg/client"
    26  
    27  	clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
    28  )
    29  
    30  const (
    31  	// ClusterClassNameField is used by the Cluster controller to index Clusters by ClusterClass name.
    32  	ClusterClassNameField = "spec.topology.class"
    33  )
    34  
    35  // ByClusterClassName adds the cluster class name  index to the
    36  // managers cache.
    37  func ByClusterClassName(ctx context.Context, mgr ctrl.Manager) error {
    38  	if err := mgr.GetCache().IndexField(ctx, &clusterv1.Cluster{},
    39  		ClusterClassNameField,
    40  		ClusterByClusterClassClassName,
    41  	); err != nil {
    42  		return errors.Wrap(err, "error setting index field")
    43  	}
    44  	return nil
    45  }
    46  
    47  // ClusterByClusterClassClassName contains the logic to index Clusters by ClusterClass name.
    48  func ClusterByClusterClassClassName(o client.Object) []string {
    49  	cluster, ok := o.(*clusterv1.Cluster)
    50  	if !ok {
    51  		panic(fmt.Sprintf("Expected Cluster but got a %T", o))
    52  	}
    53  	if cluster.Spec.Topology != nil {
    54  		return []string{cluster.Spec.Topology.Class}
    55  	}
    56  	return nil
    57  }