Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

controller: reuse the context from reconcile #385

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions controllers/clusterversion_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (

// ClusterVersionReconciler reconciles a ClusterVersion object
type ClusterVersionReconciler struct {
ctx context.Context
client.Client
Scheme *runtime.Scheme
ConsolePort int
Expand All @@ -53,9 +54,10 @@ type ClusterVersionReconciler struct {
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *ClusterVersionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx)
r.ctx = ctx
logger := log.FromContext(r.ctx)
instance := configv1.ClusterVersion{}
if err := r.Client.Get(context.TODO(), req.NamespacedName, &instance); err != nil {
if err := r.Client.Get(r.ctx, req.NamespacedName, &instance); err != nil {
return ctrl.Result{}, err
}
if err := r.ensureConsolePlugin(instance.Status.Desired.Version); err != nil {
Expand All @@ -68,8 +70,9 @@ func (r *ClusterVersionReconciler) Reconcile(ctx context.Context, req ctrl.Reque

// SetupWithManager sets up the controller with the Manager.
func (r *ClusterVersionReconciler) SetupWithManager(mgr ctrl.Manager) error {
r.ctx = context.TODO()
err := mgr.Add(manager.RunnableFunc(func(context.Context) error {
clusterVersion, err := util.DetermineOpenShiftVersion(r.Client)
clusterVersion, err := util.DetermineOpenShiftVersion(r.ctx, r.Client)
if err != nil {
return err
}
Expand All @@ -86,14 +89,14 @@ func (r *ClusterVersionReconciler) SetupWithManager(mgr ctrl.Manager) error {
}

func (r *ClusterVersionReconciler) ensureConsolePlugin(clusterVersion string) error {
logger := log.FromContext(context.TODO())
logger := log.FromContext(r.ctx)
// The base path to where the request are sent
basePath := console.GetBasePath(clusterVersion)
nginxConf := console.GetNginxConfiguration()

// Get ODF console Deployment
odfConsoleDeployment := console.GetDeployment(OperatorNamespace)
err := r.Client.Get(context.TODO(), types.NamespacedName{
err := r.Client.Get(r.ctx, types.NamespacedName{
Name: odfConsoleDeployment.Name,
Namespace: odfConsoleDeployment.Namespace,
}, odfConsoleDeployment)
Expand All @@ -103,7 +106,7 @@ func (r *ClusterVersionReconciler) ensureConsolePlugin(clusterVersion string) er

// Create/Update ODF console ConfigMap (nginx configuration)
odfConsoleConfigMap := console.GetNginxConfConfigMap(OperatorNamespace)
_, err = controllerutil.CreateOrUpdate(context.TODO(), r.Client, odfConsoleConfigMap, func() error {
_, err = controllerutil.CreateOrUpdate(r.ctx, r.Client, odfConsoleConfigMap, func() error {
if odfConsoleConfigMapData := odfConsoleConfigMap.Data["nginx.conf"]; odfConsoleConfigMapData != nginxConf {
logger.Info(fmt.Sprintf("Set the ConfigMap odf-console-nginx-conf data as '%s'", nginxConf))
odfConsoleConfigMap.Data["nginx.conf"] = nginxConf
Expand All @@ -116,7 +119,7 @@ func (r *ClusterVersionReconciler) ensureConsolePlugin(clusterVersion string) er

// Create/Update ODF console Service
odfConsoleService := console.GetService(r.ConsolePort, OperatorNamespace)
_, err = controllerutil.CreateOrUpdate(context.TODO(), r.Client, odfConsoleService, func() error {
_, err = controllerutil.CreateOrUpdate(r.ctx, r.Client, odfConsoleService, func() error {
return controllerutil.SetControllerReference(odfConsoleDeployment, odfConsoleService, r.Scheme)
})
if err != nil && !errors.IsAlreadyExists(err) {
Expand All @@ -125,7 +128,7 @@ func (r *ClusterVersionReconciler) ensureConsolePlugin(clusterVersion string) er

// Create/Update ODF console ConsolePlugin
odfConsolePlugin := console.GetConsolePluginCR(r.ConsolePort, OperatorNamespace)
_, err = controllerutil.CreateOrUpdate(context.TODO(), r.Client, odfConsolePlugin, func() error {
_, err = controllerutil.CreateOrUpdate(r.ctx, r.Client, odfConsolePlugin, func() error {
if currentBasePath := odfConsolePlugin.Spec.Service.BasePath; currentBasePath != basePath {
logger.Info(fmt.Sprintf("Set the BasePath for odf-console plugin as '%s'", basePath))
odfConsolePlugin.Spec.Service.BasePath = basePath
Expand Down
7 changes: 3 additions & 4 deletions controllers/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package controllers

import (
"context"
"fmt"

"github.com/go-logr/logr"
Expand All @@ -41,7 +40,7 @@ func (r *StorageSystemReconciler) deleteResources(instance *odfv1alpha1.StorageS
backendStorage = &ibmv1alpha1.FlashSystemCluster{}
}

err := r.Client.Get(context.TODO(), types.NamespacedName{
err := r.Client.Get(r.ctx, types.NamespacedName{
Name: instance.Spec.Name, Namespace: instance.Spec.Namespace},
backendStorage)

Expand All @@ -53,7 +52,7 @@ func (r *StorageSystemReconciler) deleteResources(instance *odfv1alpha1.StorageS
return err
}

err = r.Client.Delete(context.TODO(), backendStorage)
err = r.Client.Delete(r.ctx, backendStorage)
if err != nil {
logger.Error(err, "Failed to delete", "Kind", instance.Spec.Kind, "Name", instance.Spec.Name)
return err
Expand All @@ -67,7 +66,7 @@ func (r *StorageSystemReconciler) deleteResources(instance *odfv1alpha1.StorageS
func (r *StorageSystemReconciler) areAllStorageSystemsMarkedForDeletion(namespace string) (bool, error) {

var storageSystems odfv1alpha1.StorageSystemList
err := r.Client.List(context.TODO(), &storageSystems, &client.ListOptions{Namespace: namespace})
err := r.Client.List(r.ctx, &storageSystems, &client.ListOptions{Namespace: namespace})
if err != nil {
return false, err
}
Expand Down
7 changes: 4 additions & 3 deletions controllers/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func TestDeleteResources(t *testing.T) {
}

for i, tc := range testCases {
ctx := context.TODO()
t.Logf("Case %d: %s\n", i+1, tc.label)

fakeStorageSystem := GetFakeStorageSystem(tc.kind)
Expand All @@ -83,7 +84,7 @@ func TestDeleteResources(t *testing.T) {

fakeStorageSystem.Spec.Name = vendorSystem.GetName()
fakeStorageSystem.Spec.Namespace = vendorSystem.GetNamespace()
err = fakeReconciler.Client.Create(context.TODO(), vendorSystem)
err = fakeReconciler.Client.Create(ctx, vendorSystem)
assert.NoError(t, err)
}

Expand All @@ -93,14 +94,14 @@ func TestDeleteResources(t *testing.T) {
// verify resource does not exist
if tc.kind == VendorStorageCluster() {
storageCluster := &ocsv1.StorageCluster{}
err = fakeReconciler.Client.Get(context.TODO(), types.NamespacedName{
err = fakeReconciler.Client.Get(ctx, types.NamespacedName{
Name: fakeStorageSystem.Spec.Name, Namespace: fakeStorageSystem.Namespace},
storageCluster)
assert.True(t, errors.IsNotFound(err))

} else if tc.kind == VendorFlashSystemCluster() {
flashSystemCluster := &ibmv1alpha1.FlashSystemCluster{}
err = fakeReconciler.Client.Get(context.TODO(), types.NamespacedName{
err = fakeReconciler.Client.Get(ctx, types.NamespacedName{
Name: fakeStorageSystem.Spec.Name, Namespace: fakeStorageSystem.Namespace},
flashSystemCluster)
assert.True(t, errors.IsNotFound(err))
Expand Down
10 changes: 4 additions & 6 deletions controllers/quickstarts.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ limitations under the License.
package controllers

import (
"context"

"github.com/ghodss/yaml"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/api/errors"
Expand All @@ -41,10 +39,10 @@ func (r *StorageSystemReconciler) ensureQuickStarts(logger logr.Logger) error {
continue
}
found := consolev1.ConsoleQuickStart{}
err = r.Client.Get(context.TODO(), types.NamespacedName{Name: cqs.Name, Namespace: cqs.Namespace}, &found)
err = r.Client.Get(r.ctx, types.NamespacedName{Name: cqs.Name, Namespace: cqs.Namespace}, &found)
if err != nil {
if errors.IsNotFound(err) {
err = r.Client.Create(context.TODO(), &cqs)
err = r.Client.Create(r.ctx, &cqs)
if err != nil {
logger.Error(err, "Failed to create quickstart", "Name", cqs.Name, "Namespace", cqs.Namespace)
return nil
Expand All @@ -56,7 +54,7 @@ func (r *StorageSystemReconciler) ensureQuickStarts(logger logr.Logger) error {
return nil
}
found.Spec = cqs.Spec
err = r.Client.Update(context.TODO(), &found)
err = r.Client.Update(r.ctx, &found)
if err != nil {
logger.Error(err, "Failed to update quickstart", "Name", cqs.Name, "Namespace", cqs.Namespace)
return nil
Expand Down Expand Up @@ -90,7 +88,7 @@ func (r *StorageSystemReconciler) deleteQuickStarts(logger logr.Logger, instance
continue
}

err = r.Client.Delete(context.TODO(), &cqs)
err = r.Client.Delete(r.ctx, &cqs)
if err != nil {
if errors.IsNotFound(err) {
continue
Expand Down
5 changes: 2 additions & 3 deletions controllers/quickstarts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ func TestDeleteQuickStarts(t *testing.T) {

for i, tc := range testCases {
t.Logf("Case %d: %s\n", i+1, tc.label)

fakeReconciler := GetFakeStorageSystemReconciler(t)

err := fakeReconciler.ensureQuickStarts(fakeReconciler.Log)
Expand All @@ -150,11 +149,11 @@ func TestDeleteQuickStarts(t *testing.T) {
assert.Equal(t, 2, len(quickstarts))

for i := range tc.createStorageSystems {
err = fakeReconciler.Client.Create(context.TODO(), &tc.createStorageSystems[i])
err = fakeReconciler.Client.Create(fakeReconciler.ctx, &tc.createStorageSystems[i])
assert.NoError(t, err)
}
for i := range tc.deleteStorageSystems {
err := fakeReconciler.Client.Delete(context.TODO(), &tc.deleteStorageSystems[i])
err := fakeReconciler.Client.Delete(fakeReconciler.ctx, &tc.deleteStorageSystems[i])
assert.NoError(t, err)
err = fakeReconciler.deleteResources(&tc.deleteStorageSystems[i], fakeReconciler.Log)
assert.NoError(t, err)
Expand Down
10 changes: 6 additions & 4 deletions controllers/storagecluster_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const (

// StorageClusterReconciler reconciles a StorageCluster object
type StorageClusterReconciler struct {
ctx context.Context
client.Client
Scheme *runtime.Scheme
Recorder *EventReporter
Expand All @@ -54,10 +55,11 @@ type StorageClusterReconciler struct {
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *StorageClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx)
r.ctx = ctx
logger := log.FromContext(r.ctx)

instance := &ocsv1.StorageCluster{}
err := r.Client.Get(context.TODO(), req.NamespacedName, instance)
err := r.Client.Get(r.ctx, req.NamespacedName, instance)
if err != nil {
if errors.IsNotFound(err) {
logger.Info("StorageCluster instance not found.")
Expand All @@ -71,7 +73,7 @@ func (r *StorageClusterReconciler) Reconcile(ctx context.Context, req ctrl.Reque

// get list of StorageSystems
storageSystemList := &odfv1alpha1.StorageSystemList{}
err = r.Client.List(context.TODO(), storageSystemList, &client.ListOptions{Namespace: instance.Namespace})
err = r.Client.List(r.ctx, storageSystemList, &client.ListOptions{Namespace: instance.Namespace})
if err != nil {
logger.Error(err, "Failed to list the StorageSystem.")
return ctrl.Result{}, err
Expand All @@ -94,7 +96,7 @@ func (r *StorageClusterReconciler) Reconcile(ctx context.Context, req ctrl.Reque
}

// create StorageSystem for storageCluster
err = r.Client.Create(context.TODO(), storageSystem)
err = r.Client.Create(r.ctx, storageSystem)
if err != nil {
logger.Error(err, "Failed to create StorageSystem.", "StorageSystem", storageSystem.Name)
return ctrl.Result{}, err
Expand Down
12 changes: 7 additions & 5 deletions controllers/storagesystem_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const (
// StorageSystemReconciler reconciles a StorageSystem object
type StorageSystemReconciler struct {
client.Client
ctx context.Context
Log logr.Logger
Scheme *runtime.Scheme
Recorder *EventReporter
Expand All @@ -66,10 +67,11 @@ type StorageSystemReconciler struct {
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *StorageSystemReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
r.ctx = ctx
logger := r.Log.WithValues("instance", req.NamespacedName)

instance := &odfv1alpha1.StorageSystem{}
err := r.Client.Get(context.TODO(), req.NamespacedName, instance)
err := r.Client.Get(r.ctx, req.NamespacedName, instance)
if err != nil {
if errors.IsNotFound(err) {
logger.Info("storagesystem instance not found")
Expand All @@ -87,7 +89,7 @@ func (r *StorageSystemReconciler) Reconcile(ctx context.Context, req ctrl.Reques
result, reconcileError := r.reconcile(instance, logger)

// Apply status changes
statusError := r.Client.Status().Update(context.TODO(), instance)
statusError := r.Client.Status().Update(r.ctx, instance)
if statusError != nil {
logger.Error(statusError, "failed to update status")
}
Expand Down Expand Up @@ -178,7 +180,7 @@ func (r *StorageSystemReconciler) updateStorageSystem(instance *odfv1alpha1.Stor

// save the status locally before the Update call, as update call does not update the status and we lost it
instanceStatus := instance.Status.DeepCopy()
err := r.Client.Update(context.TODO(), instance)
err := r.Client.Update(r.ctx, instance)
instance.Status = *(instanceStatus)
return err
}
Expand Down Expand Up @@ -207,7 +209,7 @@ func (r *StorageSystemReconciler) ensureSubscriptions(instance *odfv1alpha1.Stor
}

for _, desiredSubscription := range subs {
err = EnsureDesiredSubscription(r.Client, desiredSubscription)
err = EnsureDesiredSubscription(r.ctx, r.Client, desiredSubscription)
if err != nil && !errors.IsAlreadyExists(err) {
logger.Error(err, "failed to ensure subscription", "Subscription", desiredSubscription.Name)
return err
Expand All @@ -224,7 +226,7 @@ func (r *StorageSystemReconciler) isVendorCsvReady(instance *odfv1alpha1.Storage
var returnErr error
for _, csvName := range csvNames {

csvObj, err := EnsureVendorCsv(r.Client, csvName)
csvObj, err := EnsureVendorCsv(r.ctx, r.Client, csvName)
if err != nil {
logger.Error(err, "failed to validate CSV", "ClusterServiceVersion", csvName)
multierr.AppendInto(&returnErr, err)
Expand Down
2 changes: 2 additions & 0 deletions controllers/storagesystem_controller_fake.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package controllers

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -52,6 +53,7 @@ func GetFakeStorageSystemReconciler(t *testing.T, objs ...runtime.Object) *Stora

scheme := createFakeScheme(t)
fakeStorageSystemReconciler := &StorageSystemReconciler{
ctx: context.TODO(),
Client: fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(objs...).Build(),
Log: ctrl.Log.WithName("controllers").WithName("StorageSystem"),
Scheme: scheme,
Expand Down
Loading
Loading