This repository has been archived by the owner on Oct 20, 2023. It is now read-only.
/
traffictarget_controller.go
353 lines (318 loc) · 11.4 KB
/
traffictarget_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
package traffictarget
import (
"context"
"fmt"
accessv1alpha1 "github.com/deislabs/smi-sdk-go/pkg/apis/access/v1alpha1"
specsv1alpha1 "github.com/deislabs/smi-sdk-go/pkg/apis/specs/v1alpha1"
"github.com/go-logr/logr"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
"sigs.k8s.io/controller-runtime/pkg/source"
rbacv1alpha1 "github.com/deislabs/smi-adapter-istio/pkg/apis/rbac/v1alpha1"
)
var log = logf.Log.WithName("controller_traffictarget")
// Add creates a new TrafficTarget Controller and adds it to the Manager.
// The Manager will set fields on the Controller and Start it when the Manager
// is Started.
func Add(mgr manager.Manager) error {
return add(mgr, newReconciler(mgr))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
return &ReconcileTrafficTarget{client: mgr.GetClient(),
scheme: mgr.GetScheme()}
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New("traffictarget-controller", mgr,
controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to primary resource TrafficTarget
err = c.Watch(&source.Kind{Type: &accessv1alpha1.TrafficTarget{}},
&handler.EnqueueRequestForObject{})
if err != nil {
return err
}
// Watch for changes to secondary resource ServiceRoleBindings and requeue
// the owner TrafficTarget
return c.Watch(&source.Kind{Type: &rbacv1alpha1.ServiceRoleBinding{}},
&handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &accessv1alpha1.TrafficTarget{},
})
}
var _ reconcile.Reconciler = &ReconcileTrafficTarget{}
// ReconcileTrafficTarget reconciles a TrafficTarget object
type ReconcileTrafficTarget struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
scheme *runtime.Scheme
}
// Reconcile reads that state of the cluster for a TrafficTarget object and
// makes changes based on the state read and what is in the TrafficTarget.Spec
//
// The Controller will requeue the Request to be processed again if the returned
// error is non-nil or Result.Requeue is true, otherwise upon completion it will
// remove the work from the queue.
func (r *ReconcileTrafficTarget) Reconcile(
request reconcile.Request,
) (reconcile.Result, error) {
reqLogger := log.WithValues(
"Request.Namespace", request.Namespace,
"Request.Name", request.Name)
reqLogger.Info("Reconciling TrafficTarget")
// Fetch the TrafficTarget instance
trafficTarget := &accessv1alpha1.TrafficTarget{}
err := r.client.Get(context.TODO(), request.NamespacedName, trafficTarget)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile
// request. Owned objects are automatically garbage collected. For
// additional cleanup logic use finalizers. Return and don't requeue
reqLogger.Info("TrafficTarget object not found.")
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
reqLogger.Error(err,
"Failed to get TrafficTarget. Request will be requeued.")
return reconcile.Result{}, err
}
return r.reconcileTrafficTarget(trafficTarget, reqLogger)
}
func (r *ReconcileTrafficTarget) reconcileTrafficTarget(trafficTarget *accessv1alpha1.TrafficTarget, reqLogger logr.Logger) (reconcile.Result, error) {
svcRole, svcRoleBinding, err := r.createRBAC(trafficTarget)
if err != nil {
return reconcile.Result{}, err
}
// Set TrafficTarget instance as the owner and controller
if err := controllerutil.SetControllerReference(trafficTarget,
svcRole, r.scheme); err != nil {
return reconcile.Result{}, err
}
if err := controllerutil.SetControllerReference(trafficTarget,
svcRoleBinding, r.scheme); err != nil {
return reconcile.Result{}, err
}
recSvcRole, errSvcRole := r.createServiceRole(svcRole, reqLogger)
recSvcRoleBinding, errSvcRoleBinding := r.createServiceRoleBinding(
svcRoleBinding, reqLogger,
)
if errSvcRole != nil {
return recSvcRole, errSvcRole
}
if errSvcRoleBinding != nil {
return recSvcRoleBinding, errSvcRoleBinding
}
return reconcile.Result{}, nil
}
func (r *ReconcileTrafficTarget) createServiceRole(
svcRole *rbacv1alpha1.ServiceRole,
reqLogger logr.Logger,
) (reconcile.Result, error) {
// Check if this ServiceRole already exists
foundSvcRole := &rbacv1alpha1.ServiceRole{}
err := r.client.Get(
context.TODO(),
types.NamespacedName{Name: svcRole.Name, Namespace: svcRole.Namespace},
foundSvcRole,
)
// Create ServiceRole
if err != nil && errors.IsNotFound(err) {
reqLogger.Info("Creating a new ServiceRole",
"ServiceRole.Namespace", svcRole.Namespace,
"ServiceRole.Name", svcRole.Name)
err = r.client.Create(context.TODO(), svcRole)
if err != nil {
return reconcile.Result{}, err
}
// ServiceRole created successfully - don't requeue
return reconcile.Result{}, nil
} else if err != nil {
reqLogger.Error(err, "Failed to get ServiceRole",
"ServiceRole.Namespace", svcRole.Namespace,
"ServiceRole.Name", svcRole.Name)
return reconcile.Result{}, err
}
// Update ServiceRole
if diff := cmp.Diff(svcRole.Spec, foundSvcRole.Spec); diff != "" {
reqLogger.Info("Updating ServiceRole",
"ServiceRole.Namespace", svcRole.Namespace,
"ServiceRole.Name", svcRole.Name)
clone := foundSvcRole.DeepCopy()
clone.Spec = svcRole.Spec
err = r.client.Update(context.TODO(), clone)
if err != nil {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
func (r *ReconcileTrafficTarget) createServiceRoleBinding(
svcRoleBinding *rbacv1alpha1.ServiceRoleBinding,
reqLogger logr.Logger,
) (reconcile.Result, error) {
// Check if this ServiceRoleBinding already exists
foundSvcRoleBinding := &rbacv1alpha1.ServiceRoleBinding{}
err := r.client.Get(
context.TODO(),
types.NamespacedName{
Name: svcRoleBinding.Name, Namespace: svcRoleBinding.Namespace,
},
foundSvcRoleBinding,
)
// Create ServiceRoleBinding
if err != nil && errors.IsNotFound(err) {
reqLogger.Info("Creating a new ServiceRoleBinding",
"ServiceRoleBinding.Namespace", svcRoleBinding.Namespace,
"ServiceRoleBinding.Name", svcRoleBinding.Name)
err = r.client.Create(context.TODO(), svcRoleBinding)
if err != nil {
return reconcile.Result{}, err
}
// ServiceRoleBinding created successfully - don't requeue
return reconcile.Result{}, err
} else if err != nil {
reqLogger.Error(err, "Failed to get ServiceRoleBinding",
"ServiceRoleBinding.Namespace", svcRoleBinding.Namespace,
"ServiceRoleBinding.Name", svcRoleBinding.Name)
return reconcile.Result{}, err
}
// Update ServiceRoleBinding
if diff := cmp.Diff(
svcRoleBinding.Spec, foundSvcRoleBinding.Spec,
); diff != "" {
reqLogger.Info("Updating ServiceRoleBinding",
"ServiceRoleBinding.Namespace", svcRoleBinding.Namespace,
"ServiceRoleBinding.Name", svcRoleBinding.Name)
clone := foundSvcRoleBinding.DeepCopy()
clone.Spec = svcRoleBinding.Spec
err = r.client.Update(context.TODO(), clone)
if err != nil {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
// createRBAC creates a ServiceRole and ServiceRoleBinding for each
// TrafficTarget. For all the HTTPRouteGroup objects referred in the
// TrafficTarget will also be queried.
func (r *ReconcileTrafficTarget) createRBAC(trafficTarget *accessv1alpha1.TrafficTarget) (*rbacv1alpha1.ServiceRole, *rbacv1alpha1.ServiceRoleBinding, error) {
var subjects []*rbacv1alpha1.Subject
for _, src := range trafficTarget.Sources {
// TODO:
// Remove the hardcoded value of `cluster.local`
subjects = append(subjects, &rbacv1alpha1.Subject{
User: fmt.Sprintf("cluster.local/ns/%s/sa/%s", src.Namespace, src.Name),
})
}
// same set of constraints generated from a TrafficTarget apply to all the
// AccessRules so build them early itself
constraints := getConstraints(trafficTarget.Destination)
var rules []*rbacv1alpha1.AccessRule
for _, spec := range trafficTarget.Specs {
matches, err := r.findMatches(spec, trafficTarget.Namespace)
if err != nil {
return nil, nil, err
}
for _, match := range matches {
rules = append(rules, &rbacv1alpha1.AccessRule{
// Apply to all the services, hardcoded because the
// authorization of traffic is done at constraints level
Services: []string{"*"},
Methods: match.Methods,
Paths: []string{match.PathRegex},
Constraints: constraints,
})
}
}
svcRole := &rbacv1alpha1.ServiceRole{
ObjectMeta: metav1.ObjectMeta{
Name: trafficTarget.Name,
Namespace: trafficTarget.Namespace,
},
Spec: rbacv1alpha1.ServiceRoleSpec{
Rules: rules,
},
}
svcRB := &rbacv1alpha1.ServiceRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: trafficTarget.Name,
Namespace: trafficTarget.Namespace,
},
Spec: rbacv1alpha1.ServiceRoleBindingSpec{
Subjects: subjects,
RoleRef: &rbacv1alpha1.RoleRef{
Kind: "ServiceRole",
Name: trafficTarget.Name,
},
},
}
return svcRole, svcRB, nil
}
// getConstraints reads the information from the destination object of
// TrafficTarget and creates correspoding constraints to be applied in the
// Istio ServiceRole object
func getConstraints(
dst accessv1alpha1.IdentityBindingSubject,
) []*rbacv1alpha1.AccessRule_Constraint {
constraints := []*rbacv1alpha1.AccessRule_Constraint{
{Key: "destination.user", Values: []string{dst.Name}},
{Key: "destination.namespace", Values: []string{dst.Namespace}},
}
if dst.Port != "" {
constraints = append(constraints, &rbacv1alpha1.AccessRule_Constraint{
Key: "destination.port",
Values: []string{dst.Port},
})
}
return constraints
}
// findMatches finds and returns a "match" object for a HTTPRouteGroup referred
// in the TrafficTarget, if the referred HTTPRouteGroup does not exists then it
// returns an error. If the specific match name referred in the
// `TrafficTarget.specs.matches` does not exist in the given HTTPRouteGroup
// object, then it returns an error.
func (r *ReconcileTrafficTarget) findMatches(
spec accessv1alpha1.TrafficTargetSpec, ns string,
) ([]specsv1alpha1.HTTPMatch, error) {
httpRouteGroup := &specsv1alpha1.HTTPRouteGroup{}
if err := r.client.Get(
context.TODO(),
types.NamespacedName{Namespace: ns, Name: spec.Name},
httpRouteGroup,
); err != nil {
if errors.IsNotFound(err) {
return nil, fmt.Errorf("HTTPRouteGroup not found: %v", err)
}
return nil, fmt.Errorf("Failed to get HTTPRouteGroup: %v", err)
}
// Create a map to make it easier to search later
matches := make(map[string]specsv1alpha1.HTTPMatch)
for _, match := range httpRouteGroup.Matches {
matches[match.Name] = match
}
var ret []specsv1alpha1.HTTPMatch
for _, matchName := range spec.Matches {
if _, ok := matches[matchName]; !ok {
return nil, fmt.Errorf(
"Match with name %s not found in HTTPRouteGroup %s",
matchName, spec.Name)
}
ret = append(ret, matches[matchName])
}
return ret, nil
}