Skip to content

Commit

Permalink
Fix managedclustersetrolebinding issues
Browse files Browse the repository at this point in the history
Signed-off-by: Rokibul Hasan <[email protected]>
  • Loading branch information
RokibulHasan7 committed Oct 5, 2024
1 parent 8f4b6fc commit 5f7eb76
Show file tree
Hide file tree
Showing 6 changed files with 260 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
authorizationv1alpha1 "github.com/kluster-manager/cluster-auth/apis/authorization/v1alpha1"
"github.com/kluster-manager/cluster-auth/pkg/common"

strmod "gomodules.xyz/x/strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
Expand All @@ -33,6 +34,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"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/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
Expand Down Expand Up @@ -99,8 +101,16 @@ func (r *ManagedClusterSetRoleBindingReconciler) Reconcile(ctx context.Context,
return reconcile.Result{}, err
}

if managedClusterSet.Name == "global" {
if err = r.List(ctx, &clusters); err != nil {
return reconcile.Result{}, err
}
}

clusterNameList := make([]string, 0, len(clusters.Items))
// create managedClusterRoleBinding for every cluster of this clusterSet
for _, cluster := range clusters.Items {
clusterNameList = append(clusterNameList, cluster.Name)
managedCRB := &authorizationv1alpha1.ManagedClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: managedCSRB.Name + "-" + cluster.Name,
Expand All @@ -122,6 +132,22 @@ func (r *ManagedClusterSetRoleBindingReconciler) Reconcile(ctx context.Context,
}
}

managedCRBList := &authorizationv1alpha1.ManagedClusterRoleBindingList{}
err = r.List(ctx, managedCRBList, client.MatchingLabelsSelector{
Selector: labels.SelectorFromSet(managedCSRB.Labels),
})
if err != nil {
return reconcile.Result{}, err
}

for _, crb := range managedCRBList.Items {
if !strmod.Contains(clusterNameList, crb.Namespace) {
if err = r.Delete(ctx, &crb); err != nil {
return reconcile.Result{}, err
}
}
}

return reconcile.Result{}, nil
}

Expand Down Expand Up @@ -152,9 +178,44 @@ func (r *ManagedClusterSetRoleBindingReconciler) deleteAssociatedResources(manag
return nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *ManagedClusterSetRoleBindingReconciler) mapManagedClusterSetToRoleBindings(ctx context.Context, obj client.Object) []reconcile.Request {
logger := log.FromContext(ctx)
managedClusterSet, ok := obj.(*clusterv1beta2.ManagedClusterSet)
if !ok {
return nil
}

logger.Info("ManagedClusterSet updated", "name", managedClusterSet.GetName())

managedCSRBList := &authorizationv1alpha1.ManagedClusterSetRoleBindingList{}
err := r.Client.List(ctx, managedCSRBList)
if err != nil {
logger.Error(err, "Failed to list ManagedClusterSetRoleBinding objects")
return nil
}

var requests []reconcile.Request
for _, managedCSRB := range managedCSRBList.Items {
if managedCSRB.ClusterSetRef.Name == managedClusterSet.GetName() {
// If it matches, enqueue a reconcile request for the ManagedClusterSetRoleBinding
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: managedCSRB.Name,
},
})
logger.Info("Enqueuing request", "name", managedCSRB.Name)
}
}

return requests
}

func (r *ManagedClusterSetRoleBindingReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&authorizationv1alpha1.ManagedClusterSetRoleBinding{}).
Watches(
&clusterv1beta2.ManagedClusterSet{},
handler.EnqueueRequestsFromMapFunc(r.mapManagedClusterSetToRoleBindings),
).
Complete(r)
}
60 changes: 60 additions & 0 deletions vendor/gomodules.xyz/x/strings/fmt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package strings

import (
"strings"
)

func Fmt(s string) string {
stripper := &Stripe{
Result: "",
}
stripper.Write(s)
return stripper.Result
}

// Striplines wraps an output stream, stripping runs of consecutive empty lines.
// You must call Flush before the output stream will be complete.
// Implements io.WriteCloser, Writer, Closer.
type Stripe struct {
Result string
lastLine []byte
currentLine []byte
}

func (w *Stripe) Write(p string) (int, error) {
totalN := 0
s := string(p)
if !strings.Contains(s, "\n") {
w.currentLine = append(w.currentLine, p...)
return 0, nil
}
cur := string(append(w.currentLine, p...))
lastN := strings.LastIndex(cur, "\n")
s = cur[:lastN]
for _, line := range strings.Split(s, "\n") {
n, err := w.writeLn(line + "\n")
w.lastLine = []byte(line)
if err != nil {
return totalN, err
}
totalN += n
}
rem := cur[(lastN + 1):]
w.currentLine = []byte(rem)
return totalN, nil
}

// Close flushes the last of the output into the underlying writer.
func (w *Stripe) Close() error {
_, err := w.writeLn(string(w.currentLine))
return err
}

func (w *Stripe) writeLn(line string) (n int, err error) {
if strings.TrimSpace(string(w.lastLine)) == "" && strings.TrimSpace(line) == "" {
return 0, nil
} else {
w.Result = w.Result + line
return len(line), nil
}
}
14 changes: 14 additions & 0 deletions vendor/gomodules.xyz/x/strings/optionals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package strings

import "log"

func VString(def string, args ...string) string {
v := def
if len(args) == 1 {
v = args[0]
} else if len(args) > 1 {
v = args[0]
log.Printf("Found more than 1 argument when expected 1 %v", args)
}
return v
}
11 changes: 11 additions & 0 deletions vendor/gomodules.xyz/x/strings/preconditions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package strings

import "strings"

func Val(v string, def string) string {
trimmed := strings.TrimSpace(v)
if trimmed == "" {
return def
}
return trimmed
}
112 changes: 112 additions & 0 deletions vendor/gomodules.xyz/x/strings/strings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package strings

import (
"sort"
"strings"
"unicode/utf8"
)

// Benchmark 19246 ns/op.
func Reverse(s string) string {
size := len(s)
buf := make([]byte, size)
for start := 0; start < size; {
r, n := utf8.DecodeRuneInString(s[start:])
start += n
utf8.EncodeRune(buf[size-start:], r)
}
return string(buf)
}

func PrefixFold(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(prefix, s[:len(prefix)])
}

func IsEmpty(s *string) bool {
return s == nil || *s == ""
}

func IsBothAlphaNum(a string) bool {
alpha := false
num := false
for _, c := range a {
if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') {
alpha = true
} else if c >= '0' && c <= '9' {
num = true
}
if alpha && num {
return true
}
}
return false
}

func Contains(a []string, e string) bool {
for _, s := range a {
if s == e {
return true
}
}
return false
}

// Allowed char: [a-z0-9]([a-z0-9-]*[a-z0-9])?
// Makes it safe as a subdomain
func DomainForm(s string) string {
runes := make([]rune, len(s))
for i, r := range strings.ToLower(s) {
if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'z') || (r == '-') || (r == '.') {
runes[i] = r
} else if r == '_' {
runes[i] = '-' // _ --> -
}
}
return strings.Trim(string(runes), "-")
}

func Filter(s []string, f func(string) bool) []string {
ret := make([]string, 0)
for _, elm := range s {
if !f(elm) {
ret = append(ret, elm)
}
}
return ret
}

func Join(a []*string, sep string) string {
b := make([]string, len(a))
for i, s := range a {
b[i] = *s
}
return strings.Join(b, sep)
}

func EqualSlice(a, b []string) bool {
if a == nil && b == nil {
return true
}

if a == nil || b == nil {
return false
}

if len(a) != len(b) {
return false
}

// Copy slices
aCopy := append([]string(nil), a...)
bCopy := append([]string(nil), b...)

sort.Strings(aCopy)
sort.Strings(bCopy)

for i := range aCopy {
if aCopy[i] != bCopy[i] {
return false
}
}
return true
}
1 change: 1 addition & 0 deletions vendor/modules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ gomodules.xyz/sets
gomodules.xyz/wait
# gomodules.xyz/x v0.0.17
## explicit; go 1.22.0
gomodules.xyz/x/strings
gomodules.xyz/x/version
# google.golang.org/appengine v1.6.8
## explicit; go 1.11
Expand Down

0 comments on commit 5f7eb76

Please sign in to comment.