-
Notifications
You must be signed in to change notification settings - Fork 181
/
controller.go
378 lines (328 loc) · 13.5 KB
/
controller.go
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package configurableroutes
import (
"context"
"fmt"
"strings"
configv1 "github.com/openshift/api/config/v1"
logf "github.com/openshift/cluster-ingress-operator/pkg/log"
operatorcontroller "github.com/openshift/cluster-ingress-operator/pkg/operator/controller"
util "github.com/openshift/cluster-ingress-operator/pkg/util"
"github.com/openshift/library-go/pkg/operator/events"
"github.com/openshift/library-go/pkg/operator/resource/resourceapply"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
ControllerName = "configurable_route_controller"
componentRouteHashLabelKey = "ingress.operator.openshift.io/component-route-hash"
)
var (
log = logf.Logger.WithName(ControllerName)
)
// New creates the configurable route controller from configuration. This is the controller
// that handles all the logic for generating roles and rolebindings for operators that
// include routes with configurable hostnames and serving certificates.
//
// Cluster-admins may provide a custom hostname and serving certificate for a route
// by creating a spec.componentRoute entry in the ingresses.config.openshift.io/cluster
// resource. If a componentRoute entry exists in the status.componentRoutes list with
// a matching namespace and name this controller will generate:
// - A role that grants get/list/watch permissions for the secret defined in the spec.
// - A roleBinding that binds the aforementioned role to each consumingUser specified
// in the corresponding status entry.
func New(mgr manager.Manager, config Config, eventRecorder events.Recorder) (controller.Controller, error) {
kubeClient, err := kubernetes.NewForConfig(mgr.GetConfig())
if err != nil {
return nil, err
}
operatorCache := mgr.GetCache()
reconciler := &reconciler{
kclient: kubeClient,
config: config,
client: mgr.GetClient(),
cache: operatorCache,
eventRecorder: eventRecorder,
}
c, err := controller.New(ControllerName, mgr, controller.Options{Reconciler: reconciler})
if err != nil {
return nil, err
}
// Trigger reconcile requests for the cluster ingress resource.
clusterNamePredicate := predicate.NewPredicateFuncs(func(o client.Object) bool {
clusterIngressResource := operatorcontroller.IngressClusterConfigName()
return o.GetName() == clusterIngressResource.Name && o.GetNamespace() == clusterIngressResource.Namespace
})
if err := c.Watch(source.Kind(operatorCache, &configv1.Ingress{}), &handler.EnqueueRequestForObject{}, clusterNamePredicate); err != nil {
return nil, err
}
// Trigger reconcile requests for the roles and roleBindings with the componentRoute label.
defaultPredicate := predicate.NewPredicateFuncs(func(o client.Object) bool {
labels := o.GetLabels()
_, ok := labels[componentRouteHashLabelKey]
return ok
})
if err := c.Watch(source.Kind(operatorCache, &rbacv1.Role{}), handler.EnqueueRequestsFromMapFunc(reconciler.resourceToClusterIngressConfig), defaultPredicate); err != nil {
return nil, err
}
if err := c.Watch(source.Kind(operatorCache, &rbacv1.RoleBinding{}), handler.EnqueueRequestsFromMapFunc(reconciler.resourceToClusterIngressConfig), defaultPredicate); err != nil {
return nil, err
}
return c, nil
}
// resourceToClusterIngressConfig is used to only trigger reconciles on the cluster ingress config.
func (r *reconciler) resourceToClusterIngressConfig(ctx context.Context, o client.Object) []reconcile.Request {
return []reconcile.Request{
{
NamespacedName: operatorcontroller.IngressClusterConfigName(),
},
}
}
// Config holds all the things necessary for the controller to run.
type Config struct {
SecretNamespace string
}
// reconciler handles the actual ingress reconciliation logic in response to
// events.
type reconciler struct {
config Config
client client.Client
kclient kubernetes.Interface
cache cache.Cache
eventRecorder events.Recorder
}
// Reconcile expects request to refer to the
// ingresses.config.openshift.io/cluster object and will do all the work to
// ensure that RBAC for any configured component routes is in the desired state.
func (r *reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
log.Info("reconciling", "request", request)
// Only proceed if we can get the ingress resource.
ingress := &configv1.Ingress{}
if err := r.cache.Get(ctx, request.NamespacedName, ingress); err != nil {
if apierrors.IsNotFound(err) {
log.Info("ingress cr not found; reconciliation will be skipped", "request", request)
return reconcile.Result{}, nil
}
return reconcile.Result{}, fmt.Errorf("failed to get ingress %q: %w", request.NamespacedName, err)
}
// Get the list of componentRoutes defined in both the spec and status of the ingress resource that require
// roles and roleBindings.
componentRoutes := intersectingComponentRoutes(ingress.Spec.ComponentRoutes, ingress.Status.ComponentRoutes)
// Ensure role and roleBindings exist for each valid componentRoute.
for _, componentRoute := range componentRoutes {
// Ensure role.
roleName, err := r.ensureServiceCertKeyPairSecretRole(componentRoute)
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed to create role: %v", err)
}
// Get the role just created so the UID is available for the ownerReference on the roleBinding.
role := &rbacv1.Role{}
if err := r.client.Get(ctx, types.NamespacedName{Namespace: r.config.SecretNamespace, Name: roleName}, role); err != nil {
return reconcile.Result{}, err
}
// Ensure roleBinding.
if err := r.ensureServiceCertKeyPairSecretRoleBinding(role, componentRoute); err != nil {
return reconcile.Result{}, fmt.Errorf("failed to create roleBinding: %v", err)
}
}
existingHashes := sets.String{}
for _, cr := range componentRoutes {
existingHashes.Insert(cr.Hash)
}
// Delete any roles or roleBindings that were generated for componentRoutes that are no longer defined.
// RoleBindings are cleanedup by garbage collector due to owner reference to Role.
if err := utilerrors.NewAggregate(r.deleteOrphanedRoles(componentRoutes, existingHashes)); err != nil {
return reconcile.Result{}, fmt.Errorf("error(s) deleting orphaned roles: %v", err)
}
return reconcile.Result{}, nil
}
// newAggregatedComponentRoute returns an aggregatedComponentRoute.
func newAggregatedComponentRoute(spec configv1.ComponentRouteSpec, status configv1.ComponentRouteStatus) aggregatedComponentRoute {
// Copy the list of consuming users.
consumingUsersCopy := make([]configv1.ConsumingUser, len(status.ConsumingUsers))
copy(consumingUsersCopy, status.ConsumingUsers)
return aggregatedComponentRoute{
Name: spec.Name,
Hash: util.Hash(namespacedName(spec.Namespace, spec.Name)),
ServingCertificateName: spec.ServingCertKeyPairSecret.Name,
ConsumingUsers: consumingUsersCopy,
}
}
// aggregatedComponeRoute contains information from the ComponentRouteSpec
// and ComponentRouteStatus to generate the required Role and RoleBinding.
type aggregatedComponentRoute struct {
Name string
Hash string
ServingCertificateName string
ConsumingUsers []configv1.ConsumingUser
}
// getSubjects returns a list of subjects defined in the aggregatedComponentRoute.
func (componentRoute *aggregatedComponentRoute) getSubjects() []rbacv1.Subject {
subjects := []rbacv1.Subject{}
for _, consumingUser := range componentRoute.ConsumingUsers {
splitConsumingUser := strings.Split(string(consumingUser), ":")
// Ignore invalid consuming users.
if len(splitConsumingUser) != 4 {
continue
}
switch splitConsumingUser[1] {
case "serviceaccount":
subjects = append(subjects, rbacv1.Subject{
Kind: rbacv1.ServiceAccountKind,
APIGroup: "",
Name: splitConsumingUser[3],
Namespace: splitConsumingUser[2],
})
}
}
return subjects
}
// requiresRBAC returns a boolean indicating if the componentRoute requires roles or rolebindings to be generated.
func (componentRoute *aggregatedComponentRoute) requiresRBAC() bool {
// Do not generate RBAC if no consuming users exist.
if len(componentRoute.getSubjects()) == 0 {
return false
}
// Do not generate RBAC if no secret is specified.
if componentRoute.ServingCertificateName == "" {
return false
}
return true
}
// intersectingComponentRoutes takes a slice of componentRouteSpec and a slice
// of componentRouteStatus, identifies which (namespace,name) tuples appear in
// both slices, and returns a slice of aggregatedComponentRoute corresponding to
// those tuples if they require Roles and RoleBindings.
func intersectingComponentRoutes(componentRouteSpecs []configv1.ComponentRouteSpec, componentRouteStatuses []configv1.ComponentRouteStatus) []aggregatedComponentRoute {
componentRouteHashToComponentRouteStatus := map[string]configv1.ComponentRouteStatus{}
for _, componentRouteStatus := range componentRouteStatuses {
componentRouteHash := util.Hash(namespacedName(componentRouteStatus.Namespace, componentRouteStatus.Name))
componentRouteHashToComponentRouteStatus[componentRouteHash] = componentRouteStatus
}
componentRoutes := []aggregatedComponentRoute{}
for _, componentRouteSpec := range componentRouteSpecs {
hash := util.Hash(namespacedName(componentRouteSpec.Namespace, componentRouteSpec.Name))
if componentRouteStatus, ok := componentRouteHashToComponentRouteStatus[hash]; ok {
componentRoute := newAggregatedComponentRoute(componentRouteSpec, componentRouteStatus)
if componentRoute.requiresRBAC() {
componentRoutes = append(componentRoutes, componentRoute)
}
}
}
return componentRoutes
}
func namespacedName(namespace, name string) string {
return fmt.Sprintf("%s/%s", namespace, name)
}
func componentRouteResources(componentRoute aggregatedComponentRoute) []client.ListOption {
return []client.ListOption{
client.MatchingLabels{
componentRouteHashLabelKey: componentRoute.Hash,
},
client.InNamespace(operatorcontroller.GlobalUserSpecifiedConfigNamespace),
}
}
func allComponentRouteResources() []client.ListOption {
return []client.ListOption{
client.HasLabels{componentRouteHashLabelKey},
client.InNamespace(operatorcontroller.GlobalUserSpecifiedConfigNamespace),
}
}
func (r *reconciler) deleteOrphanedRoles(componentRoutes []aggregatedComponentRoute, existingHashes sets.String) []error {
errors := []error{}
roleList := &rbacv1.RoleList{}
if err := r.cache.List(context.TODO(), roleList, allComponentRouteResources()...); err != nil {
return append(errors, err)
}
for _, item := range roleList.Items {
expectedHash, ok := item.GetLabels()[componentRouteHashLabelKey]
if !ok {
errors = append(errors, fmt.Errorf("Unable to find componentRoute hash label on role %s/%s", item.GetNamespace(), item.GetName()))
continue
}
if !existingHashes.Has(expectedHash) {
log.Info("deleting role", "name", item.GetName(), "namespace", item.GetNamespace())
if err := r.client.Delete(context.TODO(), &item); err != nil && !apierrors.IsNotFound(err) {
errors = append(errors, err)
}
}
}
return errors
}
func (r *reconciler) ensureServiceCertKeyPairSecretRole(componentRoute aggregatedComponentRoute) (string, error) {
role := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
GenerateName: componentRoute.Name + "-",
Namespace: r.config.SecretNamespace,
Labels: map[string]string{
componentRouteHashLabelKey: componentRoute.Hash,
},
},
Rules: []rbacv1.PolicyRule{
{
Verbs: []string{"get", "list", "watch"},
APIGroups: []string{""},
Resources: []string{"secrets"},
ResourceNames: []string{componentRoute.ServingCertificateName},
},
},
}
roleList := &rbacv1.RoleList{}
if err := r.cache.List(context.TODO(), roleList, componentRouteResources(componentRoute)...); err != nil {
return "", err
}
if len(roleList.Items) == 0 {
if err := r.client.Create(context.TODO(), role); err != nil {
return "", err
}
} else {
role.Name = roleList.Items[0].Name
role.GenerateName = ""
if _, _, err := resourceapply.ApplyRole(context.TODO(), r.kclient.RbacV1(), r.eventRecorder, role); err != nil {
return "", err
}
}
return role.GetName(), nil
}
func (r *reconciler) ensureServiceCertKeyPairSecretRoleBinding(role *rbacv1.Role, componentRoute aggregatedComponentRoute) error {
if role == nil {
return fmt.Errorf("cannot be passed nil role")
}
roleBinding := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: role.GetName(),
Namespace: r.config.SecretNamespace,
Labels: map[string]string{
componentRouteHashLabelKey: componentRoute.Hash,
},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: rbacv1.SchemeGroupVersion.String(),
Kind: "Role",
Name: role.GetName(),
UID: role.GetUID(),
},
},
},
Subjects: componentRoute.getSubjects(),
RoleRef: rbacv1.RoleRef{
Kind: "Role",
Name: role.GetName(),
APIGroup: rbacv1.GroupName,
},
}
_, _, err := resourceapply.ApplyRoleBinding(context.TODO(), r.kclient.RbacV1(), r.eventRecorder, roleBinding)
return err
}