-
Notifications
You must be signed in to change notification settings - Fork 787
/
controller_role.go
454 lines (413 loc) · 12.5 KB
/
controller_role.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package cmd
import (
"io"
"reflect"
"time"
"strings"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1/terminal"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
)
// ControllerRoleOptions the command line options
type ControllerRoleOptions struct {
ControllerOptions
NoWatch bool
Roles map[string]*rbacv1.Role
EnvRoleBindings map[string]*v1.EnvironmentRoleBinding
}
type ControllerRoleFlags struct {
Version string
}
const blankSting = ""
var (
controllerRoleLong = templates.LongDesc(`
Controller which replicas Role and EnvironmentRoleBinding resources to Roles and RoleBindings in all matching Environment namespaces.
RBAC in Kubernetes is either global with ClusterRoles or is namespace based with Roles per Namespace.
We use a Custom Resource called EnvironmentRoleBinding which binds Roles and its bindings from the development
environment into each Environment's Namespace.
e.g. each EnvironmentRoleBinding will result in a RoleBinding and Role resource being create in each matching Environment.
So when a Preview environment is created it will have the correct Role and RoleBinding resources added.
`)
controllerRoleExample = templates.Examples(`
# watch for changes in Role and EnvironmentRoleBindings in the dev namespace
# and update the Role + RoleBinding resources in each environment namespace
jx controller role
# update the current RoleBinding resources in each environment based on the current EnvironmentRoleBindings
jx controller role --no-watch
`)
)
func NewCmdControllerRole(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := ControllerRoleOptions{
ControllerOptions: ControllerOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "role",
Short: "Controller which mirrors Role & EnvironmentRoleBinding resources to Roles and RoleBindings in all matching Environment namespaces",
Long: controllerRoleLong,
Example: controllerRoleExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
cmd.Flags().BoolVarP(&options.NoWatch, "no-watch", "n", false, "To disable watching of the resources - to enable one-shot mode")
return cmd
}
func (o *ControllerRoleOptions) Run() error {
apiClient, err := o.CreateApiExtensionsClient()
if err != nil {
return err
}
err = kube.RegisterEnvironmentCRD(apiClient)
if err != nil {
return err
}
err = kube.RegisterEnvironmentRoleBindingCRD(apiClient)
if err != nil {
return err
}
jxClient, ns, err := o.JXClient()
if err != nil {
return err
}
kubeClient, _, err := o.KubeClient()
if err != nil {
return err
}
if !o.NoWatch {
err = o.WatchRoles(kubeClient, ns)
if err != nil {
return err
}
err = o.WatchEnvironmentRoleBindings(jxClient, ns)
if err != nil {
return err
}
err = o.WatchEnvironments(kubeClient, jxClient, ns)
if err != nil {
return err
}
}
roles, err := kubeClient.RbacV1().Roles(ns).List(metav1.ListOptions{})
if err != nil {
return err
}
for _, role := range roles.Items {
o.upsertRole(&role)
}
bindings, err := jxClient.JenkinsV1().EnvironmentRoleBindings(ns).List(metav1.ListOptions{})
if err != nil {
return err
}
for _, binding := range bindings.Items {
o.upsertEnvironmentRoleBinding(&binding)
}
envList, err := jxClient.JenkinsV1().Environments(ns).List(metav1.ListOptions{})
if err != nil {
return err
}
for _, env := range envList.Items {
err = o.upsertEnvironment(kubeClient, ns, &env)
if err != nil {
return err
}
}
o.upsertRoleIntoEnvRole(ns, jxClient)
return nil
}
func (o *ControllerRoleOptions) WatchRoles(kubeClient kubernetes.Interface, ns string) error {
role := &rbacv1.Role{}
listWatch := cache.NewListWatchFromClient(kubeClient.RbacV1().RESTClient(), "roles", ns, fields.Everything())
kube.SortListWatchByName(listWatch)
_, controller := cache.NewInformer(
listWatch,
role,
time.Minute*10,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
o.onRole(nil, obj)
},
UpdateFunc: func(oldObj, newObj interface{}) {
o.onRole(oldObj, newObj)
},
DeleteFunc: func(obj interface{}) {
o.onRole(obj, nil)
},
},
)
stop := make(chan struct{})
go controller.Run(stop)
return nil
}
func (o *ControllerRoleOptions) WatchEnvironmentRoleBindings(jxClient versioned.Interface, ns string) error {
environmentRoleBinding := &v1.EnvironmentRoleBinding{}
listWatch := cache.NewListWatchFromClient(jxClient.JenkinsV1().RESTClient(), "environmentrolebindings", ns, fields.Everything())
kube.SortListWatchByName(listWatch)
_, controller := cache.NewInformer(
listWatch,
environmentRoleBinding,
time.Minute*10,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
o.onEnvironmentRoleBinding(nil, obj)
},
UpdateFunc: func(oldObj, newObj interface{}) {
o.onEnvironmentRoleBinding(oldObj, newObj)
},
DeleteFunc: func(obj interface{}) {
o.onEnvironmentRoleBinding(obj, nil)
},
},
)
stop := make(chan struct{})
go controller.Run(stop)
return nil
}
func (o *ControllerRoleOptions) WatchEnvironments(kubeClient kubernetes.Interface, jxClient versioned.Interface, ns string) error {
environment := &v1.Environment{}
listWatch := cache.NewListWatchFromClient(jxClient.JenkinsV1().RESTClient(), "environments", ns, fields.Everything())
kube.SortListWatchByName(listWatch)
_, controller := cache.NewInformer(
listWatch,
environment,
time.Minute*10,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
o.onEnvironment(kubeClient, ns, nil, obj)
},
UpdateFunc: func(oldObj, newObj interface{}) {
o.onEnvironment(kubeClient, ns, oldObj, newObj)
},
DeleteFunc: func(obj interface{}) {
o.onEnvironment(kubeClient, ns, obj, nil)
},
},
)
stop := make(chan struct{})
go controller.Run(stop)
// Wait forever
select {}
}
func (o *ControllerRoleOptions) onEnvironment(kubeClient kubernetes.Interface, ns string, oldObj interface{}, newObj interface{}) {
var newEnv *v1.Environment
if newObj != nil {
newEnv = newObj.(*v1.Environment)
}
if oldObj != nil {
oldEnv := oldObj.(*v1.Environment)
if oldEnv != nil {
if newEnv == nil || newEnv.Spec.Namespace != oldEnv.Spec.Namespace {
err := o.removeEnvironment(kubeClient, ns, oldEnv)
if err != nil {
log.Warnf("Failed to remove role bindings for environment %s: %s", oldEnv.Name, err)
}
}
}
}
if newEnv != nil {
err := o.upsertEnvironment(kubeClient, ns, newEnv)
if err != nil {
log.Warnf("Failed to upsert role bindings for environment %s: %s", newEnv.Name, err)
}
}
}
func (o *ControllerRoleOptions) upsertEnvironment(kubeClient kubernetes.Interface, curNs string, env *v1.Environment) error {
var answer error
ns := env.Spec.Namespace
if ns != "" {
for _, binding := range o.EnvRoleBindings {
if kube.EnvironmentMatchesAny(env, binding.Spec.Environments) {
var err error
if ns != curNs {
roleName := binding.Spec.RoleRef.Name
role := o.Roles[roleName]
if role == nil {
log.Warnf("Cannot find role %s in namespace %s", roleName, curNs)
} else {
roles := kubeClient.RbacV1().Roles(ns)
var oldRole *rbacv1.Role
oldRole, err = roles.Get(roleName, metav1.GetOptions{})
if err == nil && oldRole != nil {
// lets update it
changed := false
if !reflect.DeepEqual(oldRole.Rules, role.Rules) {
oldRole.Rules = role.Rules
changed = true
}
if changed {
log.Infof("Updating Role %s in namespace %s\n", roleName, ns)
_, err = roles.Update(oldRole)
}
} else {
log.Infof("Creating Role %s in namespace %s\n", roleName, ns)
newRole := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: roleName,
Labels: map[string]string{
kube.LabelCreatedBy: kube.ValueCreatedByJX,
kube.LabelTeam: curNs,
},
},
Rules: role.Rules,
}
_, err = roles.Create(newRole)
}
}
}
bindingName := binding.Name
roleBindings := kubeClient.RbacV1().RoleBindings(ns)
var old *rbacv1.RoleBinding
old, err = roleBindings.Get(bindingName, metav1.GetOptions{})
if err == nil && old != nil {
// lets update it
changed := false
if !reflect.DeepEqual(old.RoleRef, binding.Spec.RoleRef) {
old.RoleRef = binding.Spec.RoleRef
changed = true
}
if !reflect.DeepEqual(old.Subjects, binding.Spec.Subjects) {
old.Subjects = binding.Spec.Subjects
changed = true
}
if changed {
log.Infof("Updating RoleBinding %s in namespace %s\n", bindingName, ns)
_, err = roleBindings.Update(old)
}
} else {
log.Infof("Creating RoleBinding %s in namespace %s\n", bindingName, ns)
newBinding := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: bindingName,
Labels: map[string]string{
kube.LabelCreatedBy: kube.ValueCreatedByJX,
kube.LabelTeam: curNs,
},
},
Subjects: binding.Spec.Subjects,
RoleRef: binding.Spec.RoleRef,
}
_, err = roleBindings.Create(newBinding)
}
if err != nil {
log.Warnf("Failed: %s\n", err)
if answer == nil {
answer = err
}
}
}
}
}
return answer
}
func (o *ControllerRoleOptions) removeEnvironment(kubeClient kubernetes.Interface, curNs string, env *v1.Environment) error {
ns := env.Spec.Namespace
if ns != "" {
for _, binding := range o.EnvRoleBindings {
if kube.EnvironmentMatchesAny(env, binding.Spec.Environments) {
// ignore errors
kubeClient.RbacV1().RoleBindings(ns).Delete(binding.Name, nil)
}
}
}
return nil
}
func (o *ControllerRoleOptions) onEnvironmentRoleBinding(oldObj interface{}, newObj interface{}) {
if o.EnvRoleBindings == nil {
o.EnvRoleBindings = map[string]*v1.EnvironmentRoleBinding{}
}
if oldObj != nil {
oldEnv := oldObj.(*v1.EnvironmentRoleBinding)
if oldEnv != nil {
delete(o.EnvRoleBindings, oldEnv.Name)
}
}
if newObj != nil {
newEnv := newObj.(*v1.EnvironmentRoleBinding)
o.upsertEnvironmentRoleBinding(newEnv)
}
}
func (o *ControllerRoleOptions) upsertEnvironmentRoleBinding(newEnv *v1.EnvironmentRoleBinding) {
if newEnv != nil {
if o.EnvRoleBindings == nil {
o.EnvRoleBindings = map[string]*v1.EnvironmentRoleBinding{}
}
o.EnvRoleBindings[newEnv.Name] = newEnv
}
}
func (o *ControllerRoleOptions) onRole(oldObj interface{}, newObj interface{}) {
if o.Roles == nil {
o.Roles = map[string]*rbacv1.Role{}
}
if oldObj != nil {
oldRole := oldObj.(*rbacv1.Role)
if oldRole != nil {
delete(o.Roles, oldRole.Name)
}
}
if newObj != nil {
newRole := newObj.(*rbacv1.Role)
o.upsertRole(newRole)
}
}
func (o *ControllerRoleOptions) upsertRole(newRole *rbacv1.Role) {
if newRole != nil {
if o.Roles == nil {
o.Roles = map[string]*rbacv1.Role{}
}
o.Roles[newRole.Name] = newRole
}
}
func (o *ControllerRoleOptions) upsertRoleIntoEnvRole(ns string, jxClient versioned.Interface) {
foundRole := 0
for _, roleValue := range o.Roles {
for labelK, labelV := range roleValue.Labels {
if util.StringMatchesPattern(labelK, kube.LabelKind) && util.StringMatchesPattern(labelV, kube.ValueKindEnvironmentRole) {
for _, envRoleValue := range o.EnvRoleBindings {
if util.StringMatchesPattern(strings.Trim(roleValue.GetName(), blankSting), strings.Trim(envRoleValue.Spec.RoleRef.Name, blankSting)) {
foundRole = 1
break
}
}
if foundRole == 0 {
log.Infof("Environment binding doesn't exist for role %s , creating it.\n", util.ColorInfo(roleValue.GetName()))
newSubject := rbacv1.Subject{
Name: roleValue.GetName(),
Kind: kube.ValueKindEnvironmentRole,
Namespace: ns,
}
newEnvRoleBinding := &v1.EnvironmentRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: roleValue.GetName(),
Namespace: ns,
},
Spec: v1.EnvironmentRoleBindingSpec{
Subjects: []rbacv1.Subject{
newSubject,
},
},
}
jxClient.JenkinsV1().EnvironmentRoleBindings(ns).Create(newEnvRoleBinding)
}
}
}
}
}