This repository has been archived by the owner on Dec 14, 2023. It is now read-only.
/
iamroleserviceaccount_controller.go
400 lines (340 loc) · 12.9 KB
/
iamroleserviceaccount_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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package controllers
import (
"context"
"fmt"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
k8s "k8s.io/apimachinery/pkg/api/errors"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
api "github.com/VoodooTeam/irsa-operator/api/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type fullNamer interface {
FullName() string
}
func NewIrsaReconciler(client client.Client, scheme *runtime.Scheme, logger logr.Logger) *IamRoleServiceAccountReconciler {
return &IamRoleServiceAccountReconciler{
Client: client,
scheme: scheme,
log: logger,
finalizerID: "irsa.irsa.voodoo.io",
}
}
// IamRoleServiceAccountReconciler reconciles a IamRoleServiceAccount object
type IamRoleServiceAccountReconciler struct {
client.Client
log logr.Logger
scheme *runtime.Scheme
finalizerID string
}
// +kubebuilder:rbac:groups=irsa.voodoo.io,resources=iamroleserviceaccounts,verbs=get;list;watch;create;update;delete
// +kubebuilder:rbac:groups=irsa.voodoo.io,resources=iamroleserviceaccounts/status,verbs=get;update
// +kubebuilder:rbac:groups=irsa.voodoo.io,resources=iamroleserviceaccounts/finalizers,verbs=update
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;delete
// Reconcile is called each time an event occurs on an api.IamRoleServiceAccount resource
func (r *IamRoleServiceAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var irsa *api.IamRoleServiceAccount
{ // extract role from the request
var ok bool
irsa, ok = r.getIrsaFromReq(ctx, req)
if !ok { // didn't complete, requeing
return ctrl.Result{Requeue: true}, nil
}
if irsa == nil { // not found, has been deleted
return ctrl.Result{}, nil
}
}
{ // finalizer registration & execution
if irsa.IsPendingDeletion() {
if ok := r.executeFinalizerIfPresent(ctx, irsa); !ok {
return ctrl.Result{Requeue: true}, nil
}
// ok, no requeue
return ctrl.Result{}, nil
} else {
if ok := r.registerFinalizerIfNeeded(irsa); !ok {
return ctrl.Result{Requeue: true}, nil
}
}
}
if irsa.Status.Condition == api.IrsaSubmitted { // the resource has just been created
return r.admissionStep(ctx, irsa)
}
// for whatever condition we'll try to check the role and policy actually exists
return r.reconcilerRoutine(ctx, irsa)
}
// SetupWithManager sets up the controller with the Manager.
func (r *IamRoleServiceAccountReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&api.IamRoleServiceAccount{}).
Owns(&api.Role{}).
Owns(&api.Policy{}).
Owns(&corev1.ServiceAccount{}).
WithOptions(controller.Options{
MaxConcurrentReconciles: 10,
}).
Complete(r)
}
//
// privates
//
// admissionStep does spec validation
func (r *IamRoleServiceAccountReconciler) admissionStep(ctx context.Context, irsa *api.IamRoleServiceAccount) (ctrl.Result, error) {
{ //validation
if err := irsa.Validate(); err != nil { // the iamroleserviceaccount spec is invalid
ok := r.updateStatus(ctx, irsa, api.IamRoleServiceAccountStatus{Condition: api.IrsaFailed, Reason: err.Error()})
return ctrl.Result{Requeue: !ok}, nil
}
}
{ //conflict check
if r.saWithNameExistsInNs(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace) { // serviceAccountName conflicts with an existing one
ok := r.updateStatus(ctx, irsa, api.IamRoleServiceAccountStatus{Condition: api.IrsaFailed, Reason: "serviceAccountName conflict"})
return ctrl.Result{Requeue: !ok}, nil
}
}
ok := r.updateStatus(ctx, irsa, api.IamRoleServiceAccountStatus{Condition: api.IrsaProgressing, Reason: "passed validation"})
return ctrl.Result{Requeue: !ok}, nil
}
// reconcilerRoutine is an infinite loop attempting to make the policy, role, service_account converge to the irsa.Spec
func (r *IamRoleServiceAccountReconciler) reconcilerRoutine(ctx context.Context, irsa *api.IamRoleServiceAccount) (ctrl.Result, error) {
var policyAlreadyExists, roleAlreadyExists, saAlreadyExists bool
{ // policy creation
var ok bool
policyAlreadyExists, ok = r.policyAlreadyExists(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace)
if !ok {
return ctrl.Result{Requeue: true}, nil
}
if !policyAlreadyExists { // create policy
ok := r.createPolicy(ctx, irsa)
return ctrl.Result{Requeue: !ok}, nil
} else { // update policy
if ok := r.updatePolicyIfNeeded(ctx, irsa); !ok {
return ctrl.Result{Requeue: true}, nil
}
}
}
{ // role creation
var ok bool
roleAlreadyExists, ok = r.roleAlreadyExists(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace)
if !ok {
return ctrl.Result{Requeue: true}, nil
}
if !roleAlreadyExists {
ok := r.createRole(ctx, irsa)
return ctrl.Result{Requeue: !ok}, nil
}
}
{ // service_account creation
var ok bool
saAlreadyExists, ok = r.saAlreadyExists(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace)
if !ok {
return ctrl.Result{Requeue: true}, nil
}
if !saAlreadyExists {
if r.roleIsOk(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace) &&
r.policyIsOK(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace) { // role & policy have been successfully created
if ok := r.createServiceAccount(ctx, irsa); !ok {
return ctrl.Result{Requeue: true}, nil
}
}
}
}
{ // set the status to ok
if policyAlreadyExists &&
roleAlreadyExists &&
saAlreadyExists &&
irsa.Status.Condition != api.IrsaOK {
ok := r.updateStatus(ctx, irsa, api.IamRoleServiceAccountStatus{Condition: api.IrsaOK, Reason: "all resources successfully created"})
return ctrl.Result{Requeue: !ok}, nil
}
}
return ctrl.Result{}, nil
}
func (r *IamRoleServiceAccountReconciler) executeFinalizerIfPresent(ctx context.Context, irsa *api.IamRoleServiceAccount) bool {
if !containsString(irsa.ObjectMeta.Finalizers, r.finalizerID) {
// no finalizer to execute
return true
}
{ // we delete the sa we created
sa := &corev1.ServiceAccount{}
if err := r.Get(ctx, types.NamespacedName{Namespace: irsa.ObjectMeta.Namespace, Name: irsa.ObjectMeta.Name}, sa); err != nil {
if !k8serrors.IsNotFound(err) {
r.controllerErrLog(irsa, "get sa", err)
return false
}
}
{ // ensure it is not owned by another operator
owned := false
for _, or := range sa.GetOwnerReferences() {
if or.UID == irsa.UID {
owned = true
break
}
}
if owned { // we delete the service account
if err := r.Delete(ctx, sa); err != nil && !k8serrors.IsNotFound(err) {
r.controllerErrLog(irsa, "delete sa", err)
return false
}
}
}
}
{ // delete the irsa CR
if err := r.Delete(ctx, irsa); err != nil && !k8serrors.IsNotFound(err) {
r.controllerErrLog(irsa, "delete irsa", err)
return false
}
}
// we remove the finalizer
irsa.ObjectMeta.Finalizers = removeString(irsa.ObjectMeta.Finalizers, r.finalizerID)
return r.Update(context.Background(), irsa) == nil
}
func (r *IamRoleServiceAccountReconciler) getIrsaFromReq(ctx context.Context, req ctrl.Request) (*api.IamRoleServiceAccount, bool) {
irsa := &api.IamRoleServiceAccount{}
if err := r.Get(ctx, req.NamespacedName, irsa); err != nil {
return nil, k8serrors.IsNotFound(err)
}
return irsa, true
}
func (r IamRoleServiceAccountReconciler) roleIsOk(ctx context.Context, name, ns string) bool {
role := &api.Role{}
if err := r.Client.Get(ctx, types.NamespacedName{Name: name, Namespace: ns}, role); err != nil {
return false
}
return role.Status.Condition == api.CrOK
}
func (r IamRoleServiceAccountReconciler) policyIsOK(ctx context.Context, name, ns string) bool {
policy := &api.Policy{}
if err := r.Client.Get(ctx, types.NamespacedName{Name: name, Namespace: ns}, policy); err != nil {
return false
}
return policy.Status.Condition == api.CrOK
}
func (r *IamRoleServiceAccountReconciler) policyAlreadyExists(ctx context.Context, name, ns string) (bool, bool) {
return r.resourceExists(ctx, name, ns, &api.Policy{})
}
func (r *IamRoleServiceAccountReconciler) roleAlreadyExists(ctx context.Context, name, ns string) (bool, bool) {
return r.resourceExists(ctx, name, ns, &api.Role{})
}
func (r *IamRoleServiceAccountReconciler) saAlreadyExists(ctx context.Context, name, ns string) (bool, bool) {
return r.resourceExists(ctx, name, ns, &corev1.ServiceAccount{})
}
func (r *IamRoleServiceAccountReconciler) resourceExists(ctx context.Context, name, ns string, obj client.Object) (exists bool, ok bool) {
if err := r.Client.Get(ctx, types.NamespacedName{Name: name, Namespace: ns}, obj); err != nil {
return false, k8s.IsNotFound(err)
}
return true, true
}
func (r *IamRoleServiceAccountReconciler) createPolicy(ctx context.Context, irsa *api.IamRoleServiceAccount) bool {
newPolicy := api.NewPolicy(irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace, irsa.Spec.Policy.Statement)
{ // set this irsa instance as the owner of this role
if err := ctrl.SetControllerReference(irsa, newPolicy, r.scheme); err != nil { // another resource is already the owner...
r.controllerErrLog(irsa, "set the controller reference", err)
return false
}
}
{ // create the policy resource
if err := r.Client.Create(ctx, newPolicy); err != nil { // we create it, requeue
r.controllerErrLog(irsa, "create policy", err)
return false
}
}
return true
}
func (r *IamRoleServiceAccountReconciler) updatePolicyIfNeeded(ctx context.Context, irsa *api.IamRoleServiceAccount) (ok bool) {
policy := &api.Policy{}
exists, ok := r.resourceExists(ctx, irsa.ObjectMeta.Name, irsa.ObjectMeta.Namespace, policy)
if !ok || !exists {
return false
}
policy.Spec.Statement = irsa.Spec.Policy.Statement
if err := r.Client.Update(ctx, policy); err != nil { // we update it
r.controllerErrLog(irsa, "create policy", err)
return false
}
return true
}
func (r *IamRoleServiceAccountReconciler) createRole(ctx context.Context, irsa *api.IamRoleServiceAccount) bool {
// we initialize a new role
role := api.NewRole(
irsa.ObjectMeta.Name,
irsa.ObjectMeta.Namespace,
)
// set this irsa instance as the owner of this role
if err := ctrl.SetControllerReference(irsa, role, r.scheme); err != nil { // another resource is already the owner...
r.controllerErrLog(irsa, "set controller reference", err)
return false
}
// then we create the role on k8s
if err := r.Client.Create(ctx, role); err != nil {
r.controllerErrLog(irsa, "create role", err)
return false
}
return true
}
func (r *IamRoleServiceAccountReconciler) createServiceAccount(ctx context.Context, irsa *api.IamRoleServiceAccount) (ok bool) {
role := &api.Role{}
{ // get role details
if err := r.Client.Get(ctx, types.NamespacedName{Name: irsa.ObjectMeta.Name, Namespace: irsa.ObjectMeta.Namespace}, role); err != nil {
if k8s.IsNotFound(err) {
return false
} else { // something went wrong, requeue
r.controllerErrLog(irsa, "get resource", err)
return false
}
}
}
if role.Spec.RoleARN != "" { // initialize a new serviceAccount
newServiceAccount := &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ServiceAccount",
},
ObjectMeta: metav1.ObjectMeta{
Name: irsa.ObjectMeta.Name,
Namespace: irsa.ObjectMeta.Namespace,
Annotations: map[string]string{
"eks.amazonaws.com/role-arn": role.Spec.RoleARN,
},
},
}
// set the current iamroleserviceaccount as the owner
if err := ctrl.SetControllerReference(irsa, newServiceAccount, r.scheme); err != nil { // another resource is already the owner...
r.controllerErrLog(irsa, "set controller reference", err)
return false
}
// then actually create the serviceAccount
if err := r.Client.Create(ctx, newServiceAccount); err != nil { // we create it, requeue
r.controllerErrLog(irsa, "create sa", err)
return false
}
}
return true
}
func (r *IamRoleServiceAccountReconciler) saWithNameExistsInNs(ctx context.Context, name, ns string) bool {
// a bit fragile, don't check errors other than api.NotFound
return r.Get(ctx, types.NamespacedName{Name: name, Namespace: ns}, &corev1.ServiceAccount{}) == nil
}
func (r *IamRoleServiceAccountReconciler) updateStatus(ctx context.Context, obj *api.IamRoleServiceAccount, status api.IamRoleServiceAccountStatus) bool {
obj.Status = status
return r.Status().Update(ctx, obj) == nil
}
func (r *IamRoleServiceAccountReconciler) registerFinalizerIfNeeded(role *api.IamRoleServiceAccount) bool {
if !containsString(role.ObjectMeta.Finalizers, r.finalizerID) { // the finalizer isn't registered yet
// we add it to the irsa
role.ObjectMeta.Finalizers = append(role.ObjectMeta.Finalizers, r.finalizerID)
if err := r.Update(context.Background(), role); err != nil {
r.controllerErrLog(role, "set finalizer", err)
return false
}
}
return true
}
func (r *IamRoleServiceAccountReconciler) controllerErrLog(resource fullNamer, msg string, err error) {
r.log.Info(fmt.Sprintf("[%s] : Failed to %s : %s", resource.FullName(), msg, err))
}