Skip to content

Commit

Permalink
Fix lint issues (#116)
Browse files Browse the repository at this point in the history
* Fix lint issues for goerr113

* Fix lint issues for gochecknoinits

* Fix lint issues for gofumpt

* Fix lint issues for gochecknoglobals

* Fix lint issues for stylecheck

* Fix lint issues for funlen

* Fix lint issues for nestif
  • Loading branch information
marcobebway authored Feb 8, 2024
1 parent 330d917 commit 36b77d4
Show file tree
Hide file tree
Showing 23 changed files with 350 additions and 316 deletions.
6 changes: 3 additions & 3 deletions api/v1alpha1/eventingauth_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ type AuthSecret struct {
// NamespacedName of the secret on the managed runtime cluster
NamespacedName string `json:"namespacedName"`
// Runtime ID of the cluster where the secret is created
ClusterId string `json:"clusterId"`
ClusterID string `json:"clusterId"`
}

//+kubebuilder:object:root=true
Expand All @@ -85,6 +85,6 @@ type EventingAuthList struct {
Items []EventingAuth `json:"items"`
}

func init() {
SchemeBuilder.Register(&EventingAuth{}, &EventingAuthList{})
func init() { //nolint:gochecknoinits // Used on the package level.
schemeBuilder.Register(&EventingAuth{}, &EventingAuthList{})
}
10 changes: 5 additions & 5 deletions api/v1alpha1/groupversion_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ import (
)

var (
// GroupVersion is group version used to register these objects.
GroupVersion = schema.GroupVersion{Group: "operator.kyma-project.io", Version: "v1alpha1"}
// groupVersion is group version used to register these objects.
groupVersion = schema.GroupVersion{Group: "operator.kyma-project.io", Version: "v1alpha1"} //nolint:gochecknoglobals // Used internally in the package.

// SchemeBuilder is used to add go types to the GroupVersionKind scheme.
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
// schemeBuilder is used to add go types to the GroupVersionKind scheme.
schemeBuilder = &scheme.Builder{GroupVersion: groupVersion} //nolint:gochecknoglobals // Used internally in the package.

// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
AddToScheme = schemeBuilder.AddToScheme //nolint:gochecknoglobals // Used outside the package.
)
4 changes: 2 additions & 2 deletions api/v1alpha1/status.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package v1alpha1

import (
"fmt"
"reflect"

"github.com/pkg/errors"
kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

Expand Down Expand Up @@ -39,7 +39,7 @@ func UpdateConditionAndState(eventingAuth *EventingAuth, conditionType Condition
eventingAuth.Status.Conditions = MakeSecretReadyCondition(eventingAuth, err)
}
default:
return eventingAuth.Status, fmt.Errorf("unsupported condition type: %s", conditionType)
return eventingAuth.Status, errors.Errorf("unsupported condition type: %s", conditionType)
}

if err != nil {
Expand Down
13 changes: 7 additions & 6 deletions api/v1alpha1/status_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package v1alpha1

import (
"fmt"
"testing"

"github.com/pkg/errors"
"github.com/stretchr/testify/require"
kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
Expand Down Expand Up @@ -162,7 +162,7 @@ func Test_MakeApplicationReadyCondition(t *testing.T) {
Message: ConditionMessageApplicationCreated,
},
}}),
givenErr: fmt.Errorf(mockErrorMessage),
givenErr: errors.Errorf(mockErrorMessage),
wantConditions: []kmetav1.Condition{
{
Type: string(ConditionApplicationReady),
Expand Down Expand Up @@ -262,7 +262,7 @@ func Test_MakeSecretReadyCondition(t *testing.T) {
Message: ConditionMessageSecretCreated,
},
}}),
givenErr: fmt.Errorf(mockErrorMessage),
givenErr: errors.Errorf(mockErrorMessage),
wantConditions: []kmetav1.Condition{
{
Type: string(ConditionApplicationReady),
Expand Down Expand Up @@ -319,7 +319,7 @@ func Test_UpdateConditionAndState(t *testing.T) {
State: StateReady,
}),
conditionType: ConditionSecretReady,
givenErr: fmt.Errorf(mockErrorMessage),
givenErr: errors.Errorf(mockErrorMessage),
wantStatus: EventingAuthStatus{
Conditions: []kmetav1.Condition{
{
Expand Down Expand Up @@ -416,7 +416,7 @@ func Test_UpdateConditionAndState(t *testing.T) {
State: StateNotReady,
}),
conditionType: invalidConditionType,
wantError: fmt.Errorf("unsupported condition type: %s", invalidConditionType),
wantError: errors.Errorf("unsupported condition type: %s", invalidConditionType),
},
}

Expand Down Expand Up @@ -448,6 +448,7 @@ func createTwoTrueConditions() []kmetav1.Condition {
},
}
}

func createTwoFalseConditions() []kmetav1.Condition {
return []kmetav1.Condition{
{
Expand Down Expand Up @@ -492,7 +493,7 @@ func createEventingAuthStatus(secretReadyStatus kmetav1.ConditionStatus, appName
},
AuthSecret: &AuthSecret{
NamespacedName: secretNSName,
ClusterId: "mock-cluster-reference",
ClusterID: "mock-cluster-reference",
},
State: state,
}
Expand Down
28 changes: 11 additions & 17 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,23 +37,9 @@ import (
_ "k8s.io/client-go/plugin/pkg/client/auth"
)

const webhookPort = 9443

var (
scheme = runtime.NewScheme()
setupLog = kcontrollerruntime.Log.WithName("setup")
)

func init() {
kutilruntime.Must(kscheme.AddToScheme(scheme))

kutilruntime.Must(klmapiv1beta1.AddToScheme(scheme))

kutilruntime.Must(eamapiv1alpha1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}

func main() {
const webhookPort = 9443
setupLog := kcontrollerruntime.Log.WithName("setup")
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
Expand All @@ -71,7 +57,7 @@ func main() {
kcontrollerruntime.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

mgr, err := kcontrollerruntime.NewManager(kcontrollerruntime.GetConfigOrDie(), kcontrollerruntime.Options{
Scheme: scheme,
Scheme: initScheme(),
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "210590f8.kyma-project.io",
Expand Down Expand Up @@ -127,3 +113,11 @@ func main() {
os.Exit(1)
}
}

func initScheme() *runtime.Scheme {
scheme := runtime.NewScheme()
kutilruntime.Must(kscheme.AddToScheme(scheme))
kutilruntime.Must(klmapiv1beta1.AddToScheme(scheme))
kutilruntime.Must(eamapiv1alpha1.AddToScheme(scheme))
return scheme
}
12 changes: 12 additions & 0 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package main

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_initScheme(t *testing.T) {
scheme := initScheme()
require.NotNil(t, scheme)
}
93 changes: 51 additions & 42 deletions controllers/eventingauth_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ import (
"os"
"reflect"

"github.com/go-logr/logr"
eamapiv1alpha1 "github.com/kyma-project/eventing-auth-manager/api/v1alpha1"
eamias "github.com/kyma-project/eventing-auth-manager/internal/ias"
"github.com/kyma-project/eventing-auth-manager/internal/skr"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
kcontrollerruntime "sigs.k8s.io/controller-runtime"
Expand Down Expand Up @@ -91,6 +93,10 @@ func (r *eventingAuthReconciler) Reconcile(ctx context.Context, req kcontrollerr
return kcontrollerruntime.Result{}, nil
}

return r.handleApplicationSecret(ctx, logger, cr)
}

func (r *eventingAuthReconciler) handleApplicationSecret(ctx context.Context, logger logr.Logger, cr eamapiv1alpha1.EventingAuth) (kcontrollerruntime.Result, error) {
skrClient, err := skr.NewClient(r.Client, cr.Name)
if err != nil {
logger.Error(err, "Failed to retrieve client of target cluster")
Expand All @@ -102,53 +108,56 @@ func (r *eventingAuthReconciler) Reconcile(ctx context.Context, req kcontrollerr
logger.Error(err, "Failed to retrieve secret state from target cluster")
return kcontrollerruntime.Result{}, err
}
if appSecretExists {
logger.Info("Reconciliation done, Application secret already exists")
return kcontrollerruntime.Result{}, nil
}

// TODO: check if secret creation condition is also true, otherwise it never updates false secret ready condition
if !appSecretExists {
var createAppErr error
iasApplication, appExists := r.existingIasApplications[cr.Name]
if !appExists {
logger.Info("Creating application in IAS")
iasApplication, createAppErr = r.iasClient.CreateApplication(ctx, cr.Name)
if createAppErr != nil {
logger.Error(createAppErr, "Failed to create application in IAS")
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionApplicationReady, createAppErr); err != nil {
return kcontrollerruntime.Result{}, err
}
return kcontrollerruntime.Result{}, createAppErr
}
logger.Info("Successfully created application in IAS")
r.existingIasApplications[cr.Name] = iasApplication
}
cr.Status.Application = &eamapiv1alpha1.IASApplication{
Name: cr.Name,
UUID: iasApplication.GetId(),
}
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionApplicationReady, nil); err != nil {
return kcontrollerruntime.Result{}, err
}

logger.Info("Creating application secret on SKR")
appSecret, createSecretErr := skrClient.CreateSecret(ctx, iasApplication)
if createSecretErr != nil {
logger.Error(createSecretErr, "Failed to create application secret on SKR")
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionSecretReady, createSecretErr); err != nil {
iasApplication, appExists := r.existingIasApplications[cr.Name]
if !appExists {
var createAppErr error
logger.Info("Creating application in IAS")
iasApplication, createAppErr = r.iasClient.CreateApplication(ctx, cr.Name)
if createAppErr != nil {
logger.Error(createAppErr, "Failed to create application in IAS")
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionApplicationReady, createAppErr); err != nil {
return kcontrollerruntime.Result{}, err
}
return kcontrollerruntime.Result{}, createAppErr
}
logger.Info("Successfully created application secret on SKR")

// Because the application secret is created on the SKR, we can delete it from the cache.
delete(r.existingIasApplications, cr.Name)
logger.Info("Successfully created application in IAS")
r.existingIasApplications[cr.Name] = iasApplication
}
cr.Status.Application = &eamapiv1alpha1.IASApplication{
Name: cr.Name,
UUID: iasApplication.GetID(),
}
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionApplicationReady, nil); err != nil {
return kcontrollerruntime.Result{}, err
}

cr.Status.AuthSecret = &eamapiv1alpha1.AuthSecret{
ClusterId: cr.Name,
NamespacedName: fmt.Sprintf("%s/%s", appSecret.Namespace, appSecret.Name),
}
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionSecretReady, nil); err != nil {
logger.Info("Creating application secret on SKR")
appSecret, createSecretErr := skrClient.CreateSecret(ctx, iasApplication)
if createSecretErr != nil {
logger.Error(createSecretErr, "Failed to create application secret on SKR")
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionSecretReady, createSecretErr); err != nil {
return kcontrollerruntime.Result{}, err
}
return kcontrollerruntime.Result{}, createSecretErr
}
logger.Info("Successfully created application secret on SKR")

// Because the application secret is created on the SKR, we can delete it from the cache.
delete(r.existingIasApplications, cr.Name)

cr.Status.AuthSecret = &eamapiv1alpha1.AuthSecret{
ClusterID: cr.Name,
NamespacedName: fmt.Sprintf("%s/%s", appSecret.Namespace, appSecret.Name),
}
if err := r.updateEventingAuthStatus(ctx, &cr, eamapiv1alpha1.ConditionSecretReady, nil); err != nil {
return kcontrollerruntime.Result{}, err
}

logger.Info("Reconciliation done")
Expand All @@ -168,7 +177,7 @@ func (r *eventingAuthReconciler) getIasClient() (eamias.Client, error) {
// update IAS client if credentials are changed
iasClient, err := eamias.NewClient(newIasCredentials.URL, newIasCredentials.Username, newIasCredentials.Password)
if err != nil {
return nil, fmt.Errorf("failed to createa a new IAS client: %w", err)
return nil, errors.Wrap(err, "failed to create a new IAS client")
}
return iasClient, nil
}
Expand All @@ -191,7 +200,7 @@ func (r *eventingAuthReconciler) addFinalizer(ctx context.Context, cr *eamapiv1a
kcontrollerruntime.Log.Info("Adding finalizer", "eventingAuth", cr.Name, "eventingAuthNamespace", cr.Namespace)
controllerutil.AddFinalizer(cr, eventingAuthFinalizerName)
if err := r.Update(ctx, cr); err != nil {
return fmt.Errorf("failed to add finalizer: %w", err)
return errors.Wrap(err, "failed to add finalizer")
}
}
return nil
Expand All @@ -203,7 +212,7 @@ func (r *eventingAuthReconciler) handleDeletion(ctx context.Context, iasClient e
if controllerutil.ContainsFinalizer(cr, eventingAuthFinalizerName) {
// delete IAS application clean-up
if err := iasClient.DeleteApplication(ctx, cr.Name); err != nil {
return fmt.Errorf("failed to delete IAS Application: %w", err)
return errors.Wrap(err, "failed to delete IAS Application")
}
kcontrollerruntime.Log.Info("Deleted IAS application",
"eventingAuth", cr.Name, "namespace", cr.Namespace)
Expand All @@ -218,7 +227,7 @@ func (r *eventingAuthReconciler) handleDeletion(ctx context.Context, iasClient e
// remove our finalizer from the list and update it.
controllerutil.RemoveFinalizer(cr, eventingAuthFinalizerName)
if err := r.Update(ctx, cr); err != nil {
return fmt.Errorf("failed to remove finalizer: %w", err)
return errors.Wrap(err, "failed to remove finalizer")
}
}
return nil
Expand Down Expand Up @@ -263,7 +272,7 @@ func (r *eventingAuthReconciler) updateEventingAuthStatus(ctx context.Context, c

// sync EventingAuth status with k8s
if err = r.updateStatus(ctx, actualEventingAuth, desiredEventingAuth); err != nil {
return fmt.Errorf("failed to update EventingAuth status: %w", err)
return errors.Wrap(err, "failed to update EventingAuth status")
}

return nil
Expand Down
5 changes: 3 additions & 2 deletions controllers/eventingauth_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func verifyEventingAuthStatusNotReadyAppCreationFailed(cr *eamapiv1alpha1.Eventi
string(eamapiv1alpha1.ConditionApplicationReady),
kmetav1.ConditionFalse,
eamapiv1alpha1.ConditionReasonApplicationCreationFailed,
"stubbed IAS application creation error"),
errIASApplicationCreation.Error()),
))
}, defaultTimeout).Should(Succeed())
}
Expand All @@ -239,7 +239,7 @@ func verifyEventingAuthStatusNotReadySecretCreationFailed(cr *eamapiv1alpha1.Eve
string(eamapiv1alpha1.ConditionSecretReady),
kmetav1.ConditionFalse,
eamapiv1alpha1.ConditionReasonSecretCreationFailed,
"stubbed skr secret creation error"),
errSKRSecretCreation.Error()),
))
}, defaultTimeout).Should(Succeed())
}
Expand All @@ -252,6 +252,7 @@ func conditionMatcher(t string, s kmetav1.ConditionStatus, r, m string) onsigome
"Message": Equal(m),
})
}

func deleteEventingAuthAndVerify(e *eamapiv1alpha1.EventingAuth) {
By(fmt.Sprintf("Deleting EventingAuth %s", e.Name))
if err := k8sClient.Get(context.TODO(), kpkgclient.ObjectKeyFromObject(e), &eamapiv1alpha1.EventingAuth{}); err != nil {
Expand Down
6 changes: 3 additions & 3 deletions controllers/kyma_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package controllers

import (
"context"
"fmt"
"time"

eamapiv1alpha1 "github.com/kyma-project/eventing-auth-manager/api/v1alpha1"
klmapiv1beta1 "github.com/kyma-project/lifecycle-manager/api/v1beta1"
"github.com/pkg/errors"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -67,11 +67,11 @@ func (r *KymaReconciler) createEventingAuth(ctx context.Context, kyma *klmapiv1b
}
err = r.Client.Create(ctx, eventingAuth)
if err != nil {
return fmt.Errorf("failed to create EventingAuth resource: %w", err)
return errors.Wrap(err, "failed to create EventingAuth resource")
}
return nil
}
return fmt.Errorf("failed to retrieve EventingAuth resource: %w", err)
return errors.Wrap(err, "failed to retrieve EventingAuth resource")
}
return nil
}
Expand Down
Loading

0 comments on commit 36b77d4

Please sign in to comment.