|
| 1 | +package operator |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "go.uber.org/zap" |
| 11 | + "golang.org/x/xerrors" |
| 12 | + "k8s.io/apimachinery/pkg/fields" |
| 13 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 14 | + "sigs.k8s.io/controller-runtime/pkg/controller" |
| 15 | + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" |
| 16 | + "sigs.k8s.io/controller-runtime/pkg/handler" |
| 17 | + "sigs.k8s.io/controller-runtime/pkg/manager" |
| 18 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 19 | + "sigs.k8s.io/controller-runtime/pkg/source" |
| 20 | + |
| 21 | + ctrl "sigs.k8s.io/controller-runtime" |
| 22 | + |
| 23 | + mdbv1 "github.com/mongodb/mongodb-kubernetes/api/v1/mdb" |
| 24 | + mdbmultiv1 "github.com/mongodb/mongodb-kubernetes/api/v1/mdbmulti" |
| 25 | + rolev1 "github.com/mongodb/mongodb-kubernetes/api/v1/role" |
| 26 | + "github.com/mongodb/mongodb-kubernetes/controllers/operator/watch" |
| 27 | + "github.com/mongodb/mongodb-kubernetes/controllers/operator/workflow" |
| 28 | + "github.com/mongodb/mongodb-kubernetes/mongodb-community-operator/pkg/kube/annotations" |
| 29 | + "github.com/mongodb/mongodb-kubernetes/pkg/util" |
| 30 | + "github.com/mongodb/mongodb-kubernetes/pkg/util/env" |
| 31 | +) |
| 32 | + |
| 33 | +const ( |
| 34 | + ClusterMongoDBRoleIndexForMdb = "mongodb.spec.security.roleRefs" |
| 35 | + ClusterMongoDBRoleIndexForMdbMulti = "mdbmulticluster.spec.security.roleRefs" |
| 36 | +) |
| 37 | + |
| 38 | +// ClusterMongoDBRoleReconciler reconciles a ClusterMongoDBRole object |
| 39 | +type ClusterMongoDBRoleReconciler struct { |
| 40 | + *ReconcileCommonController |
| 41 | +} |
| 42 | + |
| 43 | +// ClusterMongoDBRole Resource |
| 44 | +// +kubebuilder:rbac:groups=mongodb.com,resources={clustermongodbroles,clustermongodbroles/status,clustermongodbroles/finalizers},verbs=* |
| 45 | + |
| 46 | +func (r *ClusterMongoDBRoleReconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) { |
| 47 | + log := zap.S().With("ClusterMongoDBRole", request.NamespacedName) |
| 48 | + log.Info("-> ClusterMongoDBRole.Reconcile") |
| 49 | + |
| 50 | + role, err := r.getRole(ctx, request, log) |
| 51 | + if err != nil { |
| 52 | + log.Warnf("error getting custom role %s", err) |
| 53 | + return reconcile.Result{RequeueAfter: time.Second * util.RetryTimeSec}, nil |
| 54 | + } |
| 55 | + |
| 56 | + log.Infow("ClusterMongoDBRole.Spec", "spec", role.Spec) |
| 57 | + |
| 58 | + if err := role.ProcessValidationsOnReconcile(nil); err != nil { |
| 59 | + return r.updateStatus(ctx, role, workflow.Invalid("%s", err.Error()), log) |
| 60 | + } |
| 61 | + |
| 62 | + if !role.DeletionTimestamp.IsZero() { |
| 63 | + log.Info("ClusterMongoDBRole is being deleted") |
| 64 | + |
| 65 | + if controllerutil.ContainsFinalizer(role, util.RoleFinalizer) { |
| 66 | + return r.Delete(ctx, role, log) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if err := r.ensureFinalizer(ctx, role, log); err != nil { |
| 71 | + return r.updateStatus(ctx, role, workflow.Failed(xerrors.Errorf("Failed to add finalizer: %w", err)), log) |
| 72 | + } |
| 73 | + |
| 74 | + annotationsToAdd, err := getAnnotationsForCustomRoleResource(role) |
| 75 | + if err != nil { |
| 76 | + return r.updateStatus(ctx, role, workflow.Failed(err), log) |
| 77 | + } |
| 78 | + |
| 79 | + if err := annotations.SetAnnotations(ctx, role, annotationsToAdd, r.client); err != nil { |
| 80 | + return r.updateStatus(ctx, role, workflow.Failed(err), log) |
| 81 | + } |
| 82 | + |
| 83 | + log.Infof("Finished reconciliation for ClusterMongoDBRole!") |
| 84 | + return r.updateStatus(ctx, role, workflow.OK(), log) |
| 85 | +} |
| 86 | + |
| 87 | +func AddClusterMongoDBRoleController(ctx context.Context, mgr manager.Manager) error { |
| 88 | + reconciler := newClusterMongoDBRoleReconciler(ctx, mgr.GetClient()) |
| 89 | + c, err := controller.New(util.ClusterMongoDbRoleController, mgr, controller.Options{Reconciler: reconciler, MaxConcurrentReconciles: env.ReadIntOrDefault(util.MaxConcurrentReconcilesEnv, 1)}) // nolint:forbidigo |
| 90 | + if err != nil { |
| 91 | + return err |
| 92 | + } |
| 93 | + |
| 94 | + // Watch for changes to ClusterMongoDBRole resources |
| 95 | + // We don't need a Delete handler as there is nothing to do after removing the finalizer |
| 96 | + // To not get into an infinite reconcile loop, we ignore the delete event since the cleanup was already performed |
| 97 | + err = c.Watch(source.Kind[client.Object](mgr.GetCache(), &rolev1.ClusterMongoDBRole{}, &handler.EnqueueRequestForObject{}, watch.PredicatesForClusterRole())) |
| 98 | + if err != nil { |
| 99 | + return err |
| 100 | + } |
| 101 | + |
| 102 | + if err = mgr.GetFieldIndexer().IndexField(ctx, &mdbv1.MongoDB{}, ClusterMongoDBRoleIndexForMdb, findRolesForMongoDB); err != nil { |
| 103 | + return err |
| 104 | + } |
| 105 | + |
| 106 | + if err = mgr.GetFieldIndexer().IndexField(ctx, &mdbmultiv1.MongoDBMultiCluster{}, ClusterMongoDBRoleIndexForMdbMulti, findRolesForMongoDBMultiCluster); err != nil { |
| 107 | + return err |
| 108 | + } |
| 109 | + |
| 110 | + zap.S().Infof("Registered controller %s", util.ClusterMongoDbRoleController) |
| 111 | + return nil |
| 112 | +} |
| 113 | + |
| 114 | +func newClusterMongoDBRoleReconciler(ctx context.Context, kubeClient client.Client) *ClusterMongoDBRoleReconciler { |
| 115 | + return &ClusterMongoDBRoleReconciler{ |
| 116 | + ReconcileCommonController: NewReconcileCommonController(ctx, kubeClient), |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +func (r *ClusterMongoDBRoleReconciler) getRole(ctx context.Context, request reconcile.Request, log *zap.SugaredLogger) (*rolev1.ClusterMongoDBRole, error) { |
| 121 | + role := &rolev1.ClusterMongoDBRole{} |
| 122 | + if _, err := r.GetResource(ctx, request, role, log); err != nil { |
| 123 | + return nil, err |
| 124 | + } |
| 125 | + |
| 126 | + return role, nil |
| 127 | +} |
| 128 | + |
| 129 | +func (r *ClusterMongoDBRoleReconciler) Delete(ctx context.Context, role *rolev1.ClusterMongoDBRole, log *zap.SugaredLogger) (reconcile.Result, error) { |
| 130 | + log.Info("Attempting to remove ClusterMongoDBRole") |
| 131 | + |
| 132 | + err := r.ensureNoReferences(ctx, role) |
| 133 | + if err != nil { |
| 134 | + return r.updateStatus(ctx, role, workflow.Failed(xerrors.Errorf("Failed to remove role: %w", err)), log) |
| 135 | + } |
| 136 | + |
| 137 | + if finalizerRemoved := controllerutil.RemoveFinalizer(role, util.RoleFinalizer); !finalizerRemoved { |
| 138 | + return r.updateStatus(ctx, role, workflow.Failed(xerrors.Errorf("Failed to remove finalizer")), log) |
| 139 | + } |
| 140 | + |
| 141 | + if err := r.client.Update(ctx, role); err != nil { |
| 142 | + return r.updateStatus(ctx, role, workflow.Failed(xerrors.Errorf("Failed to update the role with the removed finalizer: %w", err)), log) |
| 143 | + } |
| 144 | + |
| 145 | + log.Info("ClusterMongoDBRole has been removed!") |
| 146 | + return r.updateStatus(ctx, role, workflow.OK(), log) |
| 147 | +} |
| 148 | + |
| 149 | +func (r *ClusterMongoDBRoleReconciler) ensureFinalizer(ctx context.Context, role *rolev1.ClusterMongoDBRole, log *zap.SugaredLogger) error { |
| 150 | + log.Info("Adding finalizer to the ClusterMongoDBRole resource") |
| 151 | + |
| 152 | + if finalizerAdded := controllerutil.AddFinalizer(role, util.RoleFinalizer); finalizerAdded { |
| 153 | + if err := r.client.Update(ctx, role); err != nil { |
| 154 | + return err |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + return nil |
| 159 | +} |
| 160 | + |
| 161 | +func (r *ClusterMongoDBRoleReconciler) ensureNoReferences(ctx context.Context, role *rolev1.ClusterMongoDBRole) error { |
| 162 | + mdbList := &mdbv1.MongoDBList{} |
| 163 | + err := r.client.List(ctx, mdbList, &client.ListOptions{ |
| 164 | + FieldSelector: fields.OneTermEqualSelector(ClusterMongoDBRoleIndexForMdb, role.Name), |
| 165 | + }) |
| 166 | + if err != nil { |
| 167 | + return err |
| 168 | + } |
| 169 | + |
| 170 | + multiList := &mdbmultiv1.MongoDBMultiClusterList{} |
| 171 | + err = r.client.List(ctx, multiList, &client.ListOptions{ |
| 172 | + FieldSelector: fields.OneTermEqualSelector(ClusterMongoDBRoleIndexForMdbMulti, role.Name), |
| 173 | + }) |
| 174 | + if err != nil { |
| 175 | + return err |
| 176 | + } |
| 177 | + |
| 178 | + if len(mdbList.Items) > 0 || len(multiList.Items) > 0 { |
| 179 | + resources := make([]string, 0) |
| 180 | + for _, mdb := range mdbList.Items { |
| 181 | + resources = append(resources, fmt.Sprintf("%s/%s", mdb.Namespace, mdb.Name)) |
| 182 | + } |
| 183 | + for _, mdbmc := range multiList.Items { |
| 184 | + resources = append(resources, fmt.Sprintf("%s/%s", mdbmc.Namespace, mdbmc.Name)) |
| 185 | + } |
| 186 | + return xerrors.Errorf("These resources are still referencing this role: %s", strings.Join(resources, ", ")) |
| 187 | + } |
| 188 | + |
| 189 | + return nil |
| 190 | +} |
| 191 | + |
| 192 | +func getAnnotationsForCustomRoleResource(role *rolev1.ClusterMongoDBRole) (map[string]string, error) { |
| 193 | + finalAnnotations := make(map[string]string) |
| 194 | + specBytes, err := json.Marshal(role.Spec) |
| 195 | + if err != nil { |
| 196 | + return nil, err |
| 197 | + } |
| 198 | + finalAnnotations[util.LastAchievedSpec] = string(specBytes) |
| 199 | + return finalAnnotations, nil |
| 200 | +} |
| 201 | + |
| 202 | +func findRolesForMongoDB(rawObj client.Object) []string { |
| 203 | + mdb := rawObj.(*mdbv1.MongoDB) |
| 204 | + roles := make([]string, 0) |
| 205 | + for _, roleRef := range mdb.Spec.Security.RoleRefs { |
| 206 | + if roleRef.Kind == util.ClusterMongoDBRoleKind { |
| 207 | + roles = append(roles, roleRef.Name) |
| 208 | + } |
| 209 | + } |
| 210 | + return roles |
| 211 | +} |
| 212 | + |
| 213 | +func findRolesForMongoDBMultiCluster(rawObj client.Object) []string { |
| 214 | + mdb := rawObj.(*mdbmultiv1.MongoDBMultiCluster) |
| 215 | + roles := make([]string, 0) |
| 216 | + for _, roleRef := range mdb.Spec.Security.RoleRefs { |
| 217 | + if roleRef.Kind == util.ClusterMongoDBRoleKind { |
| 218 | + roles = append(roles, roleRef.Name) |
| 219 | + } |
| 220 | + } |
| 221 | + return roles |
| 222 | +} |
0 commit comments