github.com/verrazzano/verrazzano@v1.7.0/cluster-operator/controllers/quickcreate/controller/controller.go (about) 1 // Copyright (c) 2023, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package controller 5 6 // Reusable code for Quick Create controllers 7 8 import ( 9 "context" 10 "github.com/verrazzano/verrazzano/pkg/k8sutil" 11 "github.com/verrazzano/verrazzano/pkg/log/vzlog" 12 vzstring "github.com/verrazzano/verrazzano/pkg/string" 13 apierrors "k8s.io/apimachinery/pkg/api/errors" 14 ctrl "sigs.k8s.io/controller-runtime" 15 clipkg "sigs.k8s.io/controller-runtime/pkg/client" 16 "time" 17 ) 18 19 type Base struct { 20 clipkg.Client 21 Log vzlog.VerrazzanoLogger 22 } 23 24 func (b *Base) SetNewResourceLogger(o clipkg.Object) error { 25 log, err := vzlog.EnsureResourceLogger(&vzlog.ResourceConfig{ 26 Name: o.GetName(), 27 Namespace: o.GetNamespace(), 28 ID: string(o.GetUID()), 29 Generation: o.GetGeneration(), 30 ControllerName: o.GetObjectKind().GroupVersionKind().Kind, 31 }) 32 if err != nil { 33 return err 34 } 35 b.Log = log 36 return nil 37 } 38 39 func (b *Base) UpdateStatus(ctx context.Context, o clipkg.Object) (ctrl.Result, error) { 40 if err := b.Status().Update(ctx, o); err != nil { 41 return RequeueDelay(), err 42 } 43 return ctrl.Result{}, nil 44 } 45 46 func (b *Base) Cleanup(ctx context.Context, o clipkg.Object, finalizerKey string) error { 47 if o.GetDeletionTimestamp().IsZero() { 48 if err := b.Delete(ctx, o); err != nil { 49 return err 50 } 51 } 52 if vzstring.SliceContainsString(o.GetFinalizers(), finalizerKey) { 53 o.SetFinalizers(vzstring.RemoveStringFromSlice(o.GetFinalizers(), finalizerKey)) 54 err := b.Update(ctx, o) 55 if err != nil && !apierrors.IsConflict(err) { 56 return err 57 } 58 } 59 return nil 60 } 61 62 func (b *Base) SetFinalizers(ctx context.Context, o clipkg.Object, finalizers ...string) (ctrl.Result, error) { 63 o.SetFinalizers(append(o.GetFinalizers(), finalizers...)) 64 if err := b.Update(ctx, o); err != nil { 65 return RequeueDelay(), err 66 } 67 return ctrl.Result{}, nil 68 } 69 70 func RequeueDelay() ctrl.Result { 71 return ctrl.Result{ 72 Requeue: true, 73 RequeueAfter: time.Duration(30) * time.Second, 74 } 75 } 76 77 func ApplyTemplates(cli clipkg.Client, props any, ns string, templates ...[]byte) error { 78 applier := k8sutil.NewYAMLApplier(cli, ns) 79 for _, tmpl := range templates { 80 if err := applier.ApplyBT(tmpl, props); err != nil { 81 return err 82 } 83 } 84 return nil 85 }