forked from knative/eventing
/
namespace.go
356 lines (311 loc) · 11 KB
/
namespace.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
/*
Copyright 2019 The Knative 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 namespace
import (
"context"
"fmt"
"github.com/knative/eventing/pkg/apis/eventing/v1alpha1"
"github.com/knative/eventing/pkg/logging"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"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/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
// controllerAgentName is the string used by this controller to identify
// itself when creating events.
controllerAgentName = "knative-eventing-namespace-controller"
// Label to enable knative-eventing in a namespace.
knativeEventingLabelKey = "knative-eventing-injection"
knativeEventingLabelValue = "enabled"
defaultBroker = "default"
brokerFilterSA = "eventing-broker-filter"
brokerFilterRB = "eventing-broker-filter"
brokerFilterClusterRole = "eventing-broker-filter"
// Name of the corev1.Events emitted from the reconciliation process.
brokerCreated = "BrokerCreated"
serviceAccountCreated = "BrokerFilterServiceAccountCreated"
serviceAccountRBACCreated = "BrokerFilterServiceAccountRBACCreated"
)
type reconciler struct {
client client.Client
recorder record.EventRecorder
logger *zap.Logger
}
// Verify the struct implements reconcile.Reconciler
var _ reconcile.Reconciler = &reconciler{}
// ProvideController returns a function that returns a Namespace controller.
func ProvideController(mgr manager.Manager, logger *zap.Logger) (controller.Controller, error) {
// Setup a new controller to Reconcile Namespaces.
r := &reconciler{
recorder: mgr.GetRecorder(controllerAgentName),
logger: logger,
}
c, err := controller.New(controllerAgentName, mgr, controller.Options{
Reconciler: r,
})
if err != nil {
return nil, err
}
// Watch Namespaces.
if err = c.Watch(&source.Kind{Type: &v1.Namespace{}}, &handler.EnqueueRequestForObject{}); err != nil {
return nil, err
}
// Watch all the resources that this reconciler reconciles. This is a map from resource type to
// the name of the resource of that type we care about (i.e. only if the resource of the given
// type and with the given name changes, do we reconcile the Namespace).
resources := map[runtime.Object]string{
&corev1.ServiceAccount{}: brokerFilterSA,
&rbacv1.RoleBinding{}: brokerFilterRB,
&v1alpha1.Broker{}: defaultBroker,
}
for t, n := range resources {
nm := &namespaceMapper{
name: n,
}
err = c.Watch(&source.Kind{Type: t}, &handler.EnqueueRequestsFromMapFunc{ToRequests: nm})
if err != nil {
return nil, err
}
}
return c, nil
}
type namespaceMapper struct {
name string
}
var _ handler.Mapper = &namespaceMapper{}
// Map implements handler.Mapper.Map.
func (m *namespaceMapper) Map(o handler.MapObject) []reconcile.Request {
if o.Meta.GetName() == m.name {
return []reconcile.Request{
{
NamespacedName: types.NamespacedName{
Namespace: "",
Name: o.Meta.GetNamespace(),
},
},
}
}
return []reconcile.Request{}
}
// InjectClient implements controller runtime's inject.Client.
func (r *reconciler) InjectClient(c client.Client) error {
r.client = c
return nil
}
// Reconcile compares the actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the Namespace resource
// with the current status of the resource.
func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) {
ctx := context.TODO()
ctx = logging.WithLogger(ctx, r.logger.With(zap.Any("request", request)))
ns := &corev1.Namespace{}
err := r.client.Get(ctx, request.NamespacedName, ns)
if errors.IsNotFound(err) {
logging.FromContext(ctx).Info("Could not find Namespace")
return reconcile.Result{}, nil
}
if err != nil {
logging.FromContext(ctx).Error("Could not Get Namespace", zap.Error(err))
return reconcile.Result{}, err
}
if ns.Labels[knativeEventingLabelKey] != knativeEventingLabelValue {
logging.FromContext(ctx).Debug("Not reconciling Namespace")
return reconcile.Result{}, nil
}
// Reconcile this copy of the Namespace and then write back any status updates regardless of
// whether the reconcile error out.
reconcileErr := r.reconcile(ctx, ns)
if reconcileErr != nil {
logging.FromContext(ctx).Error("Error reconciling Namespace", zap.Error(reconcileErr))
} else {
logging.FromContext(ctx).Debug("Namespace reconciled")
}
// Requeue if the resource is not ready:
return reconcile.Result{}, reconcileErr
}
func (r *reconciler) reconcile(ctx context.Context, ns *corev1.Namespace) error {
// No need for a finalizer, because everything reconciled is created inside the Namespace. If
// the Namespace is being deleted, then all the reconciled objects will be too.
if ns.DeletionTimestamp != nil {
return nil
}
sa, err := r.reconcileBrokerFilterServiceAccount(ctx, ns)
if err != nil {
logging.FromContext(ctx).Error("Unable to reconcile the Broker Filter Service Account for the namespace", zap.Error(err))
return err
}
_, err = r.reconcileBrokerFilterRBAC(ctx, ns, sa)
if err != nil {
logging.FromContext(ctx).Error("Unable to reconcile the Broker Filter Service Account RBAC for the namespace", zap.Error(err))
return err
}
_, err = r.reconcileBroker(ctx, ns)
if err != nil {
logging.FromContext(ctx).Error("Unable to reconcile Broker for the namespace", zap.Error(err))
return err
}
return nil
}
// reconcileBrokerFilterServiceAccount reconciles the Broker's filter service account for Namespace 'ns'.
func (r *reconciler) reconcileBrokerFilterServiceAccount(ctx context.Context, ns *corev1.Namespace) (*corev1.ServiceAccount, error) {
current, err := r.getBrokerFilterServiceAccount(ctx, ns)
// If the resource doesn't exist, we'll create it.
if k8serrors.IsNotFound(err) {
sa := newBrokerFilterServiceAccount(ns)
err = r.client.Create(ctx, sa)
if err != nil {
return nil, err
}
r.recorder.Event(ns,
corev1.EventTypeNormal,
serviceAccountCreated,
fmt.Sprintf("Service account created for the Broker '%s'", sa.Name))
return sa, nil
} else if err != nil {
return nil, err
}
// Don't update anything that is already present.
return current, nil
}
// getBrokerFilterServiceAccount returns the Broker's filter service account for Namespace 'ns' if exists,
// otherwise it returns an error.
func (r *reconciler) getBrokerFilterServiceAccount(ctx context.Context, ns *corev1.Namespace) (*corev1.ServiceAccount, error) {
sa := &corev1.ServiceAccount{}
name := types.NamespacedName{
Namespace: ns.Name,
Name: brokerFilterSA,
}
err := r.client.Get(ctx, name, sa)
return sa, err
}
// newBrokerFilterServiceAccount creates a ServiceAccount object for the Namespace 'ns'.
func newBrokerFilterServiceAccount(ns *corev1.Namespace) *corev1.ServiceAccount {
return &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns.Name,
Name: brokerFilterSA,
Labels: injectedLabels(),
},
}
}
func injectedLabels() map[string]string {
return map[string]string{
"eventing.knative.dev/namespaceInjected": "true",
}
}
// reconcileBrokerFilterRBAC reconciles the Broker's filter service account RBAC for the Namespace 'ns'.
func (r *reconciler) reconcileBrokerFilterRBAC(ctx context.Context, ns *corev1.Namespace, sa *corev1.ServiceAccount) (*rbacv1.RoleBinding, error) {
current, err := r.getBrokerFilterRBAC(ctx, ns)
// If the resource doesn't exist, we'll create it.
if k8serrors.IsNotFound(err) {
rbac := newBrokerFilterRBAC(ns, sa)
err = r.client.Create(ctx, rbac)
if err != nil {
return nil, err
}
r.recorder.Event(ns,
corev1.EventTypeNormal,
serviceAccountRBACCreated,
fmt.Sprintf("Service account RBAC created for the Broker Filter '%s'", rbac.Name))
return rbac, nil
} else if err != nil {
return nil, err
}
// Don't update anything that is already present.
return current, nil
}
// getBrokerFilterRBAC returns the Broker's filter role binding for Namespace 'ns' if exists,
// otherwise it returns an error.
func (r *reconciler) getBrokerFilterRBAC(ctx context.Context, ns *corev1.Namespace) (*rbacv1.RoleBinding, error) {
rb := &rbacv1.RoleBinding{}
name := types.NamespacedName{
Namespace: ns.Name,
Name: brokerFilterRB,
}
err := r.client.Get(ctx, name, rb)
return rb, err
}
// newBrokerFilterRBAC creates a RpleBinding object for the Broker's filter service account 'sa' in the Namespace 'ns'.
func newBrokerFilterRBAC(ns *corev1.Namespace, sa *corev1.ServiceAccount) *rbacv1.RoleBinding {
return &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns.Name,
Name: brokerFilterRB,
Labels: injectedLabels(),
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: brokerFilterClusterRole,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Namespace: ns.Name,
Name: sa.Name,
},
},
}
}
// getBroker returns the default broker for Namespace 'ns' if it exists, otherwise it returns an
// error.
func (r *reconciler) getBroker(ctx context.Context, ns *corev1.Namespace) (*v1alpha1.Broker, error) {
b := &v1alpha1.Broker{}
name := types.NamespacedName{
Namespace: ns.Name,
Name: defaultBroker,
}
err := r.client.Get(ctx, name, b)
return b, err
}
// reconcileBroker reconciles the default Broker for the Namespace 'ns'.
func (r *reconciler) reconcileBroker(ctx context.Context, ns *corev1.Namespace) (*v1alpha1.Broker, error) {
current, err := r.getBroker(ctx, ns)
// If the resource doesn't exist, we'll create it.
if k8serrors.IsNotFound(err) {
b := newBroker(ns)
err = r.client.Create(ctx, b)
if err != nil {
return nil, err
}
r.recorder.Event(ns, corev1.EventTypeNormal, brokerCreated, "Default eventing.knative.dev Broker created.")
return b, nil
} else if err != nil {
return nil, err
}
// Don't update anything that is already present.
return current, nil
}
// newBroker creates a placeholder default Broker object for Namespace 'ns'.
func newBroker(ns *corev1.Namespace) *v1alpha1.Broker {
return &v1alpha1.Broker{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns.Name,
Name: defaultBroker,
Labels: injectedLabels(),
},
}
}