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

[TT-9323] Improve policy reconcile #639

Merged
merged 7 commits into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ last reconciliation. Now, any error can be observed there instead of checking Ty

**Fixed**
- Check if certificate already exists on tyk before uploading
- Operator throwing lots of errors "the object has been modified; please apply your changes to the latest version and try again" while reconciling security policy

## [0.14.2](https://github.com/TykTechnologies/tyk-operator/tree/v0.14.2)
[Full Changelog](https://github.com/TykTechnologies/tyk-operator/compare/v0.14.1...v0.14.2)
Expand Down
25 changes: 25 additions & 0 deletions controllers/securitypolicy_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)

const policyFinalizer = "finalizers.tyk.io/securitypolicy"
Expand Down Expand Up @@ -109,6 +110,7 @@ func (r *SecurityPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reque
}

policy.Spec.SecurityPolicySpec = *newSpec

return nil
})

Expand Down Expand Up @@ -260,6 +262,7 @@ func (r *SecurityPolicyReconciler) update(ctx context.Context,
specTyk, err := klient.Universal.Portal().Policy().Get(ctx, policy.Status.PolID)
if err == nil {
if isSame(policy.Status.LatestCRDSpecHash, spec) && isSame(policy.Status.LatestTykSpecHash, specTyk) {
r.Log.Info("SecurityPolicy is already up-to-date", "Policy", client.ObjectKeyFromObject(policy))
// TODO(buraksekili): needs refactoring - no need for code duplication.
err = r.updateStatusOfLinkedAPIs(ctx, policy, false)
if err != nil {
Expand Down Expand Up @@ -446,8 +449,24 @@ func (r *SecurityPolicyReconciler) updateStatusOfLinkedAPIs(ctx context.Context,
Namespace: &namespace, Name: policy.Name,
}

oldLinks := map[string]bool{}
newLinks := map[string]bool{}

for _, t := range policy.Status.LinkedAPIs {
oldLinks[t.String()] = true
}

for _, t := range policy.Spec.AccessRightsArray {
name := types.NamespacedName{Name: t.Name, Namespace: t.Namespace}
newLinks[name.String()] = true
}

// Remove links from api definitions
for _, t := range policy.Status.LinkedAPIs {
if _, ok := newLinks[t.String()]; ok {
buraksekili marked this conversation as resolved.
Show resolved Hide resolved
continue
}

api := &tykv1.ApiDefinition{}

namespace := ""
buraksekili marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -471,6 +490,11 @@ func (r *SecurityPolicyReconciler) updateStatusOfLinkedAPIs(ctx context.Context,
}

for _, a := range policy.Spec.AccessRightsArray {
ok := oldLinks[types.NamespacedName{Name: a.Name, Namespace: a.Namespace}.String()]
buraksekili marked this conversation as resolved.
Show resolved Hide resolved
if ok && !policyDeleted {
continue
}

api := &tykv1.ApiDefinition{}

name := types.NamespacedName{Name: a.Name, Namespace: a.Namespace}
Expand Down Expand Up @@ -501,5 +525,6 @@ func (r *SecurityPolicyReconciler) updateStatusOfLinkedAPIs(ctx context.Context,
func (r *SecurityPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&tykv1.SecurityPolicy{}).
WithEventFilter(predicate.GenerationChangedPredicate{}).
Complete(r)
}
139 changes: 139 additions & 0 deletions integration/securitypolicy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1082,3 +1082,142 @@ func TestSecurityPolicyWithContextRef(t *testing.T) {

testenv.Test(t, policyAndOperatorCtx)
}

func TestUpdateStatusOfLinkedAPIs(t *testing.T) {
var (
api1 = "api1"
api2 = "api2"
testNs = ""
polName = ""
pol *v1alpha1.SecurityPolicy
)

f := features.New("UpdateStatusOfLinkedAPIs").
Setup(func(ctx context.Context, t *testing.T, c *envconf.Config) context.Context {
eval := is.New(t)
komalsukhani marked this conversation as resolved.
Show resolved Hide resolved

var ok bool
testNs, ok = ctx.Value(ctxNSKey).(string)
eval.True(ok)

// Obtain Environment configuration to be able to connect Tyk.
tykEnv, err := generateEnvConfig(ctx, c)
eval.NoErr(err)

verifyPolicyApiVersion(t, &tykEnv)

apiDef, err := createTestAPIDef(ctx, c, testNs, func(api *v1alpha1.ApiDefinition) {
api.Name = api1
api.Spec.Name = api1
})
eval.NoErr(err)

err = waitForTykResourceCreation(c, apiDef)
eval.NoErr(err)

apiDef, err = createTestAPIDef(ctx, c, testNs, func(api *v1alpha1.ApiDefinition) {
api.Name = api2
api.Spec.Name = api2
})
eval.NoErr(err)

err = waitForTykResourceCreation(c, apiDef)
eval.NoErr(err)

pol, err = createTestPolicy(ctx, c, testNs, func(p *v1alpha1.SecurityPolicy) {
p.Spec.AccessRightsArray = []*model.AccessDefinition{
{
Name: api1,
Namespace: testNs,
},
{
Name: api2,
Namespace: testNs,
},
}
})
eval.NoErr(err)

polName = pol.Name

err = waitForTykResourceCreation(c, pol)
eval.NoErr(err)

return ctx
}).Assess("Link to policy is added both apis",
buraksekili marked this conversation as resolved.
Show resolved Hide resolved
func(ctx context.Context, t *testing.T, c *envconf.Config) context.Context {
apiDef := v1alpha1.ApiDefinition{}
eval := is.New(t)

err := c.Client().Resources(testNs).Get(ctx, api1, testNs, &apiDef)
eval.NoErr(err)

eval.True(len(apiDef.Status.LinkedByPolicies) == 1)
eval.True(apiDef.Status.LinkedByPolicies[0].Name == polName)

err = c.Client().Resources(testNs).Get(ctx, api2, testNs, &apiDef)
eval.NoErr(err)

eval.True(len(apiDef.Status.LinkedByPolicies) == 1)
eval.True(apiDef.Status.LinkedByPolicies[0].Name == polName)

return ctx
}).Assess("Link to policy is removed from api2",
func(ctx context.Context, t *testing.T, c *envconf.Config) context.Context {
eval := is.New(t)

pol.Spec.AccessRightsArray = []*model.AccessDefinition{
{
Name: "api1",
Namespace: testNs,
},
}

err := c.Client().Resources(testNs).Update(ctx, pol)
eval.NoErr(err)

apiDef := v1alpha1.ApiDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: api2,
Namespace: testNs,
},
}

err = wait.For(conditions.New(c.Client().Resources()).ResourceMatch(&apiDef, func(object k8s.Object) bool {
if apiDef.Status.LinkedByPolicies == nil || len(apiDef.Status.LinkedByPolicies) == 0 {
return true
}

return false
}), wait.WithTimeout(defaultWaitTimeout), wait.WithInterval(defaultWaitInterval))
eval.NoErr(err)

return ctx
}).Assess("Link to policy is removed when policy is deleted",
func(ctx context.Context, t *testing.T, c *envconf.Config) context.Context {
eval := is.New(t)

err := c.Client().Resources(testNs).Delete(ctx, pol)
eval.NoErr(err)

apiDef := v1alpha1.ApiDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: api1,
Namespace: testNs,
},
}

err = wait.For(conditions.New(c.Client().Resources()).ResourceMatch(&apiDef, func(object k8s.Object) bool {
if apiDef.Status.LinkedByPolicies == nil || len(apiDef.Status.LinkedByPolicies) == 0 {
return true
}

return false
}), wait.WithTimeout(defaultWaitTimeout), wait.WithInterval(defaultWaitInterval))
eval.NoErr(err)

return ctx
}).Feature()

testenv.Test(t, f)
}