/* Copyright © contributors to CloudNativePG, established as CloudNativePG a Series of LF Projects, LLC. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ // Package rbac contains utilities to reconcile RBAC resources // for the barman-cloud plugin. package rbac import ( "context" cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" "github.com/cloudnative-pg/machinery/pkg/log" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" apierrs "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/client" barmancloudv1 "github.com/cloudnative-pg/plugin-barman-cloud/api/v1" "github.com/cloudnative-pg/plugin-barman-cloud/internal/cnpgi/operator/specs" ) // EnsureRole ensures the RBAC Role for the given Cluster matches // the desired state derived from the given ObjectStores. // Optional beforeCreate callbacks are applied to the Role before creation // (e.g. to set owner references). They are not called on updates. func EnsureRole( ctx context.Context, c client.Client, cluster *cnpgv1.Cluster, barmanObjects []barmancloudv1.ObjectStore, beforeCreate ...func(*rbacv1.Role) error, ) error { contextLogger := log.FromContext(ctx) newRole := specs.BuildRole(cluster, barmanObjects) var role rbacv1.Role if err := c.Get(ctx, client.ObjectKey{ Namespace: newRole.Namespace, Name: newRole.Name, }, &role); err != nil { if !apierrs.IsNotFound(err) { return err } contextLogger.Info( "Creating role", "name", newRole.Name, "namespace", newRole.Namespace, ) for _, fn := range beforeCreate { if err := fn(newRole); err != nil { return err } } return c.Create(ctx, newRole) } if equality.Semantic.DeepEqual(newRole.Rules, role.Rules) { return nil } contextLogger.Info( "Patching role", "name", newRole.Name, "namespace", newRole.Namespace, "rules", newRole.Rules, ) oldRole := role.DeepCopy() role.Rules = newRole.Rules return c.Patch(ctx, &role, client.MergeFrom(oldRole)) }