Skip to content

Commit

Permalink
Make generic controller for cluster-based resources (#259)
Browse files Browse the repository at this point in the history
* Make generic controller for cluster resources

* add error check to test
  • Loading branch information
andrewstucki authored Oct 4, 2024
1 parent 04a8ea9 commit e897bcf
Show file tree
Hide file tree
Showing 13 changed files with 724 additions and 412 deletions.
4 changes: 2 additions & 2 deletions acceptance/steps/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ func userIsSuccessfullySynced(ctx context.Context, t framework.TestingT, user st

// make sure it's synchronized
t.RequireCondition(metav1.Condition{
Type: redpandav1alpha2.UserConditionTypeSynced,
Type: redpandav1alpha2.ResourceConditionTypeSynced,
Status: metav1.ConditionTrue,
Reason: redpandav1alpha2.UserConditionReasonSynced,
Reason: redpandav1alpha2.ResourceConditionReasonSynced,
}, userObject.Status.Conditions)
}

Expand Down
30 changes: 30 additions & 0 deletions operator/api/redpanda/v1alpha2/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/redpanda-data/console/backend/pkg/config"
"github.com/twmb/franz-go/pkg/kadm"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

Expand Down Expand Up @@ -271,3 +272,32 @@ func (c *ClusterSource) GetAdminAPISpec() *AdminAPISpec {
func (c *ClusterSource) GetClusterRef() *ClusterRef {
return c.ClusterRef
}

const (
ResourceConditionTypeSynced = "Synced"

ResourceConditionReasonPending = "Pending"
ResourceConditionReasonSynced = "Synced"
ResourceConditionReasonClusterRefInvalid = "ClusterRefInvalid"
ResourceConditionReasonConfigurationInvalid = "ConfigurationInvalid"
ResourceConditionReasonTerminalClientError = "TerminalClientError"
ResourceConditionReasonUnexpectedError = "UnexpectedError"
)

func ResourceSyncedCondition(name string) metav1.Condition {
return metav1.Condition{
Type: ResourceConditionTypeSynced,
Status: metav1.ConditionTrue,
Reason: ResourceConditionReasonSynced,
Message: fmt.Sprintf("Successfully %q synced to cluster.", name),
}
}

func ResourceNotSyncedCondition(reason string, err error) metav1.Condition {
return metav1.Condition{
Type: ResourceConditionTypeSynced,
Status: metav1.ConditionFalse,
Reason: reason,
Message: fmt.Sprintf("Error: %v", err),
}
}
35 changes: 5 additions & 30 deletions operator/api/redpanda/v1alpha2/user_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ package v1alpha2
import (
"context"
"errors"
"fmt"
"slices"

"github.com/redpanda-data/redpanda-operator/operator/pkg/functional"
"github.com/twmb/franz-go/pkg/kmsg"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -460,35 +460,6 @@ func (s ACLResourceSpec) GetName() string {
return s.Name
}

const (
UserConditionTypeSynced = "Synced"

UserConditionReasonPending = "Pending"
UserConditionReasonSynced = "Synced"
UserConditionReasonClusterRefInvalid = "ClusterRefInvalid"
UserConditionReasonConfigurationInvalid = "ConfigurationInvalid"
UserConditionReasonTerminalClientError = "TerminalClientError"
UserConditionReasonUnexpectedError = "UnexpectedError"
)

func UserSyncedCondition(name string) metav1.Condition {
return metav1.Condition{
Type: UserConditionTypeSynced,
Status: metav1.ConditionTrue,
Reason: UserConditionReasonSynced,
Message: fmt.Sprintf("User %q successfully synced to cluster.", name),
}
}

func UserNotSyncedCondition(reason string, err error) metav1.Condition {
return metav1.Condition{
Type: UserConditionTypeSynced,
Status: metav1.ConditionFalse,
Reason: reason,
Message: fmt.Sprintf("Error: %v", err),
}
}

// UserStatus defines the observed state of a Redpanda user
type UserStatus struct {
// Specifies the last observed generation.
Expand All @@ -511,3 +482,7 @@ type UserList struct {
// Specifies a list of Redpanda user resources.
Items []User `json:"items"`
}

func (u *UserList) GetItems() []*User {
return functional.MapFn(ptr.To, u.Items)
}
4 changes: 2 additions & 2 deletions operator/api/redpanda/v1alpha2/user_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,9 +505,9 @@ func TestUserDefaults(t *testing.T) {
require.NoError(t, c.Get(ctx, types.NamespacedName{Namespace: metav1.NamespaceDefault, Name: "name"}, &user))

require.Len(t, user.Status.Conditions, 1)
require.Equal(t, UserConditionTypeSynced, user.Status.Conditions[0].Type)
require.Equal(t, ResourceConditionTypeSynced, user.Status.Conditions[0].Type)
require.Equal(t, metav1.ConditionUnknown, user.Status.Conditions[0].Status)
require.Equal(t, UserConditionReasonPending, user.Status.Conditions[0].Reason)
require.Equal(t, ResourceConditionReasonPending, user.Status.Conditions[0].Reason)

require.NotNil(t, user.Spec.Authentication.Type)
require.True(t, user.Spec.Authentication.Type.Equals(SASLMechanismScramSHA512))
Expand Down
5 changes: 1 addition & 4 deletions operator/cmd/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -547,10 +547,7 @@ func Run(
os.Exit(1)
}

if err = (&redpandacontrollers.UserReconciler{
Client: mgr.GetClient(),
ClientFactory: factory,
}).SetupWithManager(ctx, mgr); err != nil {
if err = redpandacontrollers.SetupUserController(ctx, mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "User")
os.Exit(1)
}
Expand Down
92 changes: 56 additions & 36 deletions operator/internal/controller/redpanda/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,55 +11,70 @@ package redpanda

import (
"context"
"fmt"
"reflect"
"slices"

redpandav1alpha2 "github.com/redpanda-data/redpanda-operator/operator/api/redpanda/v1alpha2"
"github.com/redpanda-data/redpanda-operator/operator/pkg/functional"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

const (
userClusterIndex = "__user_referencing_cluster"
deploymentClusterIndex = "__deployment_referencing_cluster"
statefulsetClusterIndex = "__statefulset_referencing_cluster"
)
type clientList[T client.Object] interface {
client.ObjectList
GetItems() []T
}

func userCluster(user *redpandav1alpha2.User) types.NamespacedName {
return types.NamespacedName{Namespace: user.Namespace, Name: user.Spec.ClusterSource.ClusterRef.Name}
func clusterReferenceIndexName(name string) string {
return fmt.Sprintf("__%s_referencing_cluster", name)
}

func registerUserClusterIndex(ctx context.Context, mgr ctrl.Manager) error {
return mgr.GetFieldIndexer().IndexField(ctx, &redpandav1alpha2.User{}, userClusterIndex, indexUserCluster)
func registerClusterSourceIndex[T client.Object, U clientList[T]](ctx context.Context, mgr ctrl.Manager, name string, o T, l U) (handler.EventHandler, error) {
indexName := clusterReferenceIndexName(name)
if err := mgr.GetFieldIndexer().IndexField(ctx, o, indexName, indexByClusterSource); err != nil {
return nil, err
}
return enqueueFromSourceCluster(mgr, name, l), nil
}

func indexUserCluster(o client.Object) []string {
user := o.(*redpandav1alpha2.User)
source := user.Spec.ClusterSource
func registerHelmReferencedIndex[T client.Object](ctx context.Context, mgr ctrl.Manager, name string, o T) error {
indexName := clusterReferenceIndexName(name)
if err := mgr.GetFieldIndexer().IndexField(ctx, o, indexName, indexHelmManagedObjectCluster); err != nil {
return err
}
return nil
}

func indexByClusterSource(o client.Object) []string {
clusterReferencingObject := o.(redpandav1alpha2.ClusterReferencingObject)
source := clusterReferencingObject.GetClusterSource()

clusters := []string{}
if source != nil && source.ClusterRef != nil {
clusters = append(clusters, userCluster(user).String())
cluster := types.NamespacedName{Namespace: clusterReferencingObject.GetNamespace(), Name: source.ClusterRef.Name}
clusters = append(clusters, cluster.String())
}

return clusters
}

func usersForCluster(ctx context.Context, c client.Client, nn types.NamespacedName) ([]reconcile.Request, error) {
childList := &redpandav1alpha2.UserList{}
err := c.List(ctx, childList, &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(userClusterIndex, nn.String()),
func sourceClusters[T client.Object, U clientList[T]](ctx context.Context, c client.Client, list U, name string, nn types.NamespacedName) ([]reconcile.Request, error) {
err := c.List(ctx, list, &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(clusterReferenceIndexName(name), nn.String()),
})
if err != nil {
return nil, err
}

requests := []reconcile.Request{}
for _, item := range childList.Items { //nolint:gocritic // this is necessary
for _, item := range list.GetItems() { //nolint:gocritic // this is necessary
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: item.GetNamespace(),
Expand All @@ -71,12 +86,16 @@ func usersForCluster(ctx context.Context, c client.Client, nn types.NamespacedNa
return requests, nil
}

func registerDeploymentClusterIndex(ctx context.Context, mgr ctrl.Manager) error {
return mgr.GetFieldIndexer().IndexField(ctx, &appsv1.Deployment{}, deploymentClusterIndex, indexHelmManagedObjectCluster)
}

func registerStatefulSetClusterIndex(ctx context.Context, mgr ctrl.Manager) error {
return mgr.GetFieldIndexer().IndexField(ctx, &appsv1.StatefulSet{}, statefulsetClusterIndex, indexHelmManagedObjectCluster)
func enqueueFromSourceCluster[T client.Object, U clientList[T]](mgr ctrl.Manager, name string, l U) handler.EventHandler {
return handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request {
list := reflect.New(reflect.TypeOf(l).Elem()).Interface().(U)
requests, err := sourceClusters(ctx, mgr.GetClient(), list, name, client.ObjectKeyFromObject(o))
if err != nil {
mgr.GetLogger().V(1).Info(fmt.Sprintf("possibly skipping %s reconciliation due to failure to fetch %s associated with cluster", name, name), "error", err)
return nil
}
return requests
})
}

func clusterForHelmManagedObject(o client.Object) (types.NamespacedName, bool) {
Expand All @@ -101,6 +120,15 @@ func clusterForHelmManagedObject(o client.Object) (types.NamespacedName, bool) {
}, true
}

func enqueueClusterFromHelmManagedObject() handler.EventHandler {
return handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request {
if nn, found := clusterForHelmManagedObject(o); found {
return []reconcile.Request{{NamespacedName: nn}}
}
return nil
})
}

func indexHelmManagedObjectCluster(o client.Object) []string {
nn, found := clusterForHelmManagedObject(o)
if !found {
Expand All @@ -123,33 +151,25 @@ func consoleDeploymentsForCluster(ctx context.Context, c client.Client, cluster

deploymentList := &appsv1.DeploymentList{}
err := c.List(ctx, deploymentList, &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(deploymentClusterIndex, key),
FieldSelector: fields.OneTermEqualSelector(clusterReferenceIndexName("deployment"), key),
})
if err != nil {
return nil, err
}

return mapFn(ptr.To, deploymentList.Items), nil
return functional.MapFn(ptr.To, deploymentList.Items), nil
}

func redpandaStatefulSetsForCluster(ctx context.Context, c client.Client, cluster *redpandav1alpha2.Redpanda) ([]*appsv1.StatefulSet, error) {
key := client.ObjectKeyFromObject(cluster).String() + "/redpanda"

ssList := &appsv1.StatefulSetList{}
err := c.List(ctx, ssList, &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(statefulsetClusterIndex, key),
FieldSelector: fields.OneTermEqualSelector(clusterReferenceIndexName("statefulset"), key),
})
if err != nil {
return nil, err
}

return mapFn(ptr.To, ssList.Items), nil
}

func mapFn[T any, U any](fn func(T) U, a []T) []U {
s := make([]U, len(a))
for i := 0; i < len(a); i++ {
s[i] = fn(a[i])
}
return s
return functional.MapFn(ptr.To, ssList.Items), nil
}
17 changes: 4 additions & 13 deletions operator/internal/controller/redpanda/redpanda_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
v2 "sigs.k8s.io/controller-runtime/pkg/webhook/conversion/testdata/api/v2"

"github.com/redpanda-data/redpanda-operator/operator/api/redpanda/v1alpha2"
Expand Down Expand Up @@ -124,10 +122,10 @@ type RedpandaReconciler struct {

// SetupWithManager sets up the controller with the Manager.
func (r *RedpandaReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
if err := registerStatefulSetClusterIndex(ctx, mgr); err != nil {
if err := registerHelmReferencedIndex(ctx, mgr, "statefulset", &appsv1.StatefulSet{}); err != nil {
return err
}
if err := registerDeploymentClusterIndex(ctx, mgr); err != nil {
if err := registerHelmReferencedIndex(ctx, mgr, "deployment", &appsv1.Deployment{}); err != nil {
return err
}

Expand All @@ -152,20 +150,13 @@ func (r *RedpandaReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Mana

managedWatchOption := builder.WithPredicates(helmManagedComponentPredicate)

enqueueRequestFromManaged := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, o client.Object) []reconcile.Request {
if nn, found := clusterForHelmManagedObject(o); found {
return []reconcile.Request{{NamespacedName: nn}}
}
return nil
})

return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha2.Redpanda{}).
Owns(&sourcev1.HelmRepository{}).
Owns(&helmv2beta1.HelmRelease{}).
Owns(&helmv2beta2.HelmRelease{}).
Watches(&appsv1.StatefulSet{}, enqueueRequestFromManaged, managedWatchOption).
Watches(&appsv1.Deployment{}, enqueueRequestFromManaged, managedWatchOption).
Watches(&appsv1.StatefulSet{}, enqueueClusterFromHelmManagedObject(), managedWatchOption).
Watches(&appsv1.Deployment{}, enqueueClusterFromHelmManagedObject(), managedWatchOption).
Complete(r)
}

Expand Down
Loading

0 comments on commit e897bcf

Please sign in to comment.