forked from kbind-dev/kbind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclusterbinding_controller.go
More file actions
266 lines (241 loc) · 9.71 KB
/
Copy pathclusterbinding_controller.go
File metadata and controls
266 lines (241 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
Copyright 2022 The Kube Bind Authors.
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.
*/
package clusterbinding
import (
"context"
"fmt"
"reflect"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/cluster"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder"
mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager"
mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile"
kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2"
bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned"
)
const (
controllerName = "kube-bind-example-backend-clusterbinding"
)
// ClusterBindingReconciler reconciles a ClusterBinding object.
type ClusterBindingReconciler struct {
manager mcmanager.Manager
scope kubebindv1alpha2.InformerScope
bindClient bindclient.Interface
reconciler reconciler
}
// NewClusterBindingReconciler returns a new ClusterBindingReconciler to reconcile ClusterBindings.
func NewClusterBindingReconciler(
mgr mcmanager.Manager,
config *rest.Config,
scope kubebindv1alpha2.InformerScope,
) (*ClusterBindingReconciler, error) {
config = rest.CopyConfig(config)
config = rest.AddUserAgent(config, controllerName)
bindClient, err := bindclient.NewForConfig(config)
if err != nil {
return nil, err
}
r := &ClusterBindingReconciler{
manager: mgr,
scope: scope,
bindClient: bindClient,
reconciler: reconciler{
scope: scope,
listServiceExports: func(ctx context.Context, cache cache.Cache, ns string) ([]*kubebindv1alpha2.APIServiceExport, error) {
var list kubebindv1alpha2.APIServiceExportList
if err := cache.List(ctx, &list, client.InNamespace(ns)); err != nil {
return nil, err
}
var exports []*kubebindv1alpha2.APIServiceExport
for i := range list.Items {
exports = append(exports, &list.Items[i])
}
return exports, nil
},
getAPIResourceSchema: func(ctx context.Context, cache cache.Cache, name string) (*kubebindv1alpha2.APIResourceSchema, error) {
result := &kubebindv1alpha2.APIResourceSchema{}
err = cache.Get(ctx, types.NamespacedName{Name: name}, result)
if err != nil {
return nil, fmt.Errorf("failed to get APIResourceSchema %q: %w", name, err)
}
return result, nil
},
getClusterRole: func(ctx context.Context, cache cache.Cache, name string) (*rbacv1.ClusterRole, error) {
var role rbacv1.ClusterRole
key := types.NamespacedName{Name: name}
if err := cache.Get(ctx, key, &role); err != nil {
return nil, err
}
return &role, nil
},
createClusterRole: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRole) (*rbacv1.ClusterRole, error) {
if err := client.Create(ctx, binding); err != nil {
return nil, err
}
return binding, nil
},
updateClusterRole: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRole) (*rbacv1.ClusterRole, error) {
if err := client.Update(ctx, binding); err != nil {
return nil, err
}
return binding, nil
},
getClusterRoleBinding: func(ctx context.Context, cache cache.Cache, name string) (*rbacv1.ClusterRoleBinding, error) {
var binding rbacv1.ClusterRoleBinding
key := types.NamespacedName{Name: name}
if err := cache.Get(ctx, key, &binding); err != nil {
return nil, err
}
return &binding, nil
},
createClusterRoleBinding: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRoleBinding) (*rbacv1.ClusterRoleBinding, error) {
if err := client.Create(ctx, binding); err != nil {
return nil, err
}
return binding, nil
},
updateClusterRoleBinding: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRoleBinding) (*rbacv1.ClusterRoleBinding, error) {
if err := client.Update(ctx, binding); err != nil {
return nil, err
}
return binding, nil
},
deleteClusterRoleBinding: func(ctx context.Context, client client.Client, name string) error {
binding := &rbacv1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{Name: name},
}
return client.Delete(ctx, binding)
},
getNamespace: func(ctx context.Context, cache cache.Cache, name string) (*v1.Namespace, error) {
var ns v1.Namespace
key := types.NamespacedName{Name: name}
if err := cache.Get(ctx, key, &ns); err != nil {
return nil, fmt.Errorf("failed to get Namespace %q: %w", name, err)
}
return &ns, nil
},
createRoleBinding: func(ctx context.Context, client client.Client, ns string, binding *rbacv1.RoleBinding) (*rbacv1.RoleBinding, error) {
binding.Namespace = ns
if err := client.Create(ctx, binding); err != nil {
return nil, err
}
return binding, nil
},
updateRoleBinding: func(ctx context.Context, client client.Client, ns string, binding *rbacv1.RoleBinding) (*rbacv1.RoleBinding, error) {
binding.Namespace = ns
if err := client.Update(ctx, binding); err != nil {
return nil, err
}
return binding, nil
},
getRoleBinding: func(ctx context.Context, cache cache.Cache, ns, name string) (*rbacv1.RoleBinding, error) {
var binding rbacv1.RoleBinding
key := types.NamespacedName{Namespace: ns, Name: name}
if err := cache.Get(ctx, key, &binding); err != nil {
return nil, fmt.Errorf("failed to get RoleBinding %q in namespace %q: %w", name, ns, err)
}
return &binding, nil
},
},
}
return r, nil
}
//+kubebuilder:rbac:groups=kubebind.k8s.io,resources=clusterbindings,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=kubebind.k8s.io,resources=clusterbindings/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=kubebind.k8s.io,resources=clusterbindings/finalizers,verbs=update
//+kubebuilder:rbac:groups=kubebind.k8s.io,resources=apiserviceexports,verbs=get;list;watch
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterroles,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=rolebindings,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups="",resources=namespaces,verbs=get;list;watch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *ClusterBindingReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx)
logger.Info("Reconciling ClusterBinding", "request", req)
cl, err := r.manager.GetCluster(ctx, req.ClusterName)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err)
}
client := cl.GetClient()
cache := cl.GetCache()
// Fetch the ClusterBinding instance
clusterBinding := &kubebindv1alpha2.ClusterBinding{}
if err := client.Get(ctx, req.NamespacedName, clusterBinding); err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
logger.Info("ClusterBinding not found, ignoring")
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
return ctrl.Result{}, fmt.Errorf("failed to get ClusterBinding: %w", err)
}
// Create a copy to modify
original := clusterBinding.DeepCopy()
// Run the reconciliation logic
if err := r.reconciler.reconcile(ctx, client, cache, clusterBinding); err != nil {
logger.Error(err, "Failed to reconcile ClusterBinding")
return ctrl.Result{}, err
}
// Update status if it has changed
if !reflect.DeepEqual(original, clusterBinding) {
err := client.Update(ctx, clusterBinding)
if err != nil {
logger.Error(err, "Failed to update ClusterBinding status")
return ctrl.Result{}, fmt.Errorf("failed to update ClusterBinding status: %w", err)
}
logger.Info("ClusterBinding status updated")
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *ClusterBindingReconciler) SetupWithManager(mgr mcmanager.Manager) error {
return mcbuilder.ControllerManagedBy(mgr).
For(&kubebindv1alpha2.ClusterBinding{}).
Owns(&rbacv1.ClusterRole{}).
Owns(&rbacv1.ClusterRoleBinding{}).
Owns(&rbacv1.RoleBinding{}).
Watches(
&kubebindv1alpha2.APIServiceExport{},
mapAPIResourceSchema,
).
Named(controllerName).
Complete(r)
}
func mapAPIResourceSchema(clusterName string, cl cluster.Cluster) handler.TypedEventHandler[client.Object, mcreconcile.Request] {
return handler.TypedEnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []mcreconcile.Request {
serviceExport, ok := obj.(*kubebindv1alpha2.APIServiceExport)
if !ok {
return nil
}
return []mcreconcile.Request{
{
Request: reconcile.Request{
NamespacedName: client.ObjectKeyFromObject(serviceExport),
},
ClusterName: clusterName,
},
}
})
}