A library to avoid overstuffed Reconcile functions of Kubernetes operators as suggested in this blog post
- Avoid overstuffed functions through handlers in a chain of responsibility
- Wrap the reconciliation results to improve the readability of your code
Install by running:
go get github.com/angelokurtis/reconciler
Split the Reconcile responsibilities into handlers with one single purpose and chain them in your controller:
// package omitted
import "github.com/angelokurtis/reconciler"
// other imports
func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// Fetch the Memcached instance
m := &cachev1alpha1.Memcached{}
err := r.Get(ctx, req.NamespacedName, m)
if err != nil {
if errors.IsNotFound(err) {
return r.Finish(ctx) // Ignoring since object must be deleted
}
return r.RequeueOnErr(ctx, err) // Failed to get Memcached
}
// Chains reconcile handlers
return reconciler.Chain(
&memcached.DeploymentCreation{Client: r.Client, Scheme: r.Scheme},
&memcached.Status{Client: r.Client},
).Reconcile(ctx, m)
}
Your handler can compose reconciler.Funcs that already implement most of the interface functions so you just need to put your logic on Reconcile(context.Context, client.Object) implementation:
// package omitted
import "github.com/angelokurtis/reconciler"
// other imports
type DeploymentCreation struct {
reconciler.Funcs
// other fields
}
func (d *DeploymentCreation) Reconcile(ctx context.Context, obj client.Object) (ctrl.Result, error) {
// TODO(user): your logic here
return d.Next(ctx, obj)
}