Skip to content

Commit

Permalink
KongUpstreamPolicy controller improved
Browse files Browse the repository at this point in the history
Signed-off-by: Mattia Lavacca <lavacca.mattia@gmail.com>
  • Loading branch information
mlavacca committed Nov 29, 2023
1 parent 187fbe6 commit 8f51be1
Show file tree
Hide file tree
Showing 11 changed files with 2,352 additions and 43 deletions.
278 changes: 278 additions & 0 deletions config/crd/bases/configuration.konghq.com_kongupstreampolicies.yaml

Large diffs are not rendered by default.

114 changes: 98 additions & 16 deletions internal/controllers/configuration/kongupstreampolicy_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,26 @@ import (
"time"

"github.com/go-logr/logr"
"github.com/kong/kubernetes-ingress-controller/v3/internal/controllers"
"github.com/kong/kubernetes-ingress-controller/v3/internal/util"
kongv1beta1 "github.com/kong/kubernetes-ingress-controller/v3/pkg/apis/configuration/v1beta1"
"github.com/samber/lo"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"

"github.com/kong/kubernetes-ingress-controller/v3/internal/controllers"
"github.com/kong/kubernetes-ingress-controller/v3/internal/gatewayapi"
"github.com/kong/kubernetes-ingress-controller/v3/internal/util"
kongv1beta1 "github.com/kong/kubernetes-ingress-controller/v3/pkg/apis/configuration/v1beta1"
)

// -----------------------------------------------------------------------------
// KongV1beta1 KongUpstreamPolicy - Reconciler
// KongUpstreamPolicy Controller - Reconciler
// -----------------------------------------------------------------------------

// KongV1beta1KongUpstreamPolicyReconciler reconciles KongUpstreamPolicy resources
Expand All @@ -46,17 +51,38 @@ func (r *KongV1beta1KongUpstreamPolicyReconciler) SetupWithManager(mgr ctrl.Mana
if err != nil {
return err
}

mgr.GetCache().IndexField(context.Background(), &corev1.Service{}, upstreamPolicyIndexKey, indexServices)

Check failure on line 55 in internal/controllers/configuration/kongupstreampolicy_controller.go

View workflow job for this annotation

GitHub Actions / tools

Error return value of `(sigs.k8s.io/controller-runtime/pkg/client.FieldIndexer).IndexField` is not checked (errcheck)

Check failure on line 55 in internal/controllers/configuration/kongupstreampolicy_controller.go

View workflow job for this annotation

GitHub Actions / linters / lint

Error return value of `(sigs.k8s.io/controller-runtime/pkg/client.FieldIndexer).IndexField` is not checked (errcheck)

return c.Watch(
source.Kind(mgr.GetCache(), &kongv1beta1.KongUpstreamPolicy{}),
&handler.EnqueueRequestForObject{},
)
}

// SetLogger sets the logger.
func (r *KongV1beta1KongUpstreamPolicyReconciler) SetLogger(l logr.Logger) {
r.Log = l
// -----------------------------------------------------------------------------
// KongUpstreamPolicy Controller - Indexers
// -----------------------------------------------------------------------------

const upstreamPolicyIndexKey = "upstreamPolicy"

func indexServices(o client.Object) []string {
service, ok := o.(*corev1.Service)
if !ok {
return []string{}
}
if service.Annotations != nil {
if policy, ok := service.Annotations[kongv1beta1.KongUpstreamPolicyAnnotationKey]; ok {
return []string{policy}
}
}
return []string{}
}

// -----------------------------------------------------------------------------
// KongUpstreamPolicy Controller - Reconciliation
// -----------------------------------------------------------------------------

//+kubebuilder:rbac:groups=configuration.konghq.com,resources=kongupstreampolicies,verbs=get;list;watch
//+kubebuilder:rbac:groups=configuration.konghq.com,resources=kongupstreampolicies/status,verbs=get;update;patch

Expand All @@ -65,40 +91,96 @@ func (r *KongV1beta1KongUpstreamPolicyReconciler) Reconcile(ctx context.Context,
log := r.Log.WithValues("KongV1beta1KongUpstreamPolicy", req.NamespacedName)

// get the relevant object
obj := new(kongv1beta1.KongUpstreamPolicy)
kongUpstreamPolicy := new(kongv1beta1.KongUpstreamPolicy)

if err := r.Get(ctx, req.NamespacedName, obj); err != nil {
if err := r.Get(ctx, req.NamespacedName, kongUpstreamPolicy); err != nil {
if apierrors.IsNotFound(err) {
obj.Namespace = req.Namespace
obj.Name = req.Name
kongUpstreamPolicy.Namespace = req.Namespace
kongUpstreamPolicy.Name = req.Name

return ctrl.Result{}, r.DataplaneClient.DeleteObject(obj)
return ctrl.Result{}, r.DataplaneClient.DeleteObject(kongUpstreamPolicy)
}
return ctrl.Result{}, err
}
log.V(util.DebugLevel).Info("Reconciling resource", "namespace", req.Namespace, "name", req.Name)

// clean the object up if it's being deleted
if !obj.DeletionTimestamp.IsZero() && time.Now().After(obj.DeletionTimestamp.Time) {
if !kongUpstreamPolicy.DeletionTimestamp.IsZero() && time.Now().After(kongUpstreamPolicy.DeletionTimestamp.Time) {
log.V(util.DebugLevel).Info("Resource is being deleted, its configuration will be removed", "type", "KongUpstreamPolicy", "namespace", req.Namespace, "name", req.Name)

objectExistsInCache, err := r.DataplaneClient.ObjectExists(obj)
objectExistsInCache, err := r.DataplaneClient.ObjectExists(kongUpstreamPolicy)
if err != nil {
return ctrl.Result{}, err
}
if objectExistsInCache {
if err := r.DataplaneClient.DeleteObject(obj); err != nil {
if err := r.DataplaneClient.DeleteObject(kongUpstreamPolicy); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil // wait until the object is no longer present in the cache
}
return ctrl.Result{}, nil
}

// get all the services that reference this UpstreamPolicy
services := &corev1.ServiceList{}
err := r.List(ctx, services,
client.InNamespace(kongUpstreamPolicy.Namespace),
client.MatchingFields{
upstreamPolicyIndexKey: kongUpstreamPolicy.Name,
},
)
if err != nil {
return ctrl.Result{}, err
}
updated, err := r.enforceKongUpstreamPolicyStatusAncestor(ctx, *kongUpstreamPolicy, services.Items)
if err != nil {
return ctrl.Result{}, err
}
if updated {
// status update will re-trigger reconciliation
return ctrl.Result{}, nil
}

// update the kong Admin API with the changes
if err := r.DataplaneClient.UpdateObject(obj); err != nil {
if err := r.DataplaneClient.UpdateObject(kongUpstreamPolicy); err != nil {
return ctrl.Result{}, err
}

return ctrl.Result{}, nil
}

// -----------------------------------------------------------------------------
// KongUpstreamPolicy Controller - Helpers
// -----------------------------------------------------------------------------

func (r *KongV1beta1KongUpstreamPolicyReconciler) enforceKongUpstreamPolicyStatusAncestor(ctx context.Context, policy kongv1beta1.KongUpstreamPolicy, services []corev1.Service) (bool, error) {
if policy.Status.Ancestors == nil {
policy.Status.Ancestors = []gatewayapi.PolicyAncestorStatus{}
}
for _, service := range services {
policy.Status.Ancestors = append(policy.Status.Ancestors,
gatewayapi.PolicyAncestorStatus{
AncestorRef: gatewayapi.ParentReference{
Group: lo.ToPtr(gatewayapi.Group("core")),
Kind: lo.ToPtr(gatewayapi.Kind("Service")),
Namespace: lo.ToPtr(gatewayapi.Namespace(service.Namespace)),
Name: gatewayapi.ObjectName(service.Name),
},
ControllerName: gatewayapi.GatewayController("test"),
Conditions: []metav1.Condition{
{
Type: string(gatewayapi.PolicyConditionAccepted),
Status: metav1.ConditionTrue,
Reason: string(gatewayapi.PolicyReasonAccepted),
},
},
},
)
}
return true, r.Client.Status().Update(ctx, &policy)
}

// SetLogger sets the logger.
func (r *KongV1beta1KongUpstreamPolicyReconciler) SetLogger(l logr.Logger) {
r.Log = l
}
55 changes: 29 additions & 26 deletions internal/gatewayapi/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,32 +71,33 @@ type (
SecretObjectReference = gatewayv1.SecretObjectReference
SectionName = gatewayv1.SectionName

GRPCBackendRef = gatewayv1alpha2.GRPCBackendRef
GRPCHeaderMatch = gatewayv1alpha2.GRPCHeaderMatch
GRPCHeaderName = gatewayv1alpha2.GRPCHeaderName
GRPCMethodMatch = gatewayv1alpha2.GRPCMethodMatch
GRPCMethodMatchType = gatewayv1alpha2.GRPCMethodMatchType
GRPCRoute = gatewayv1alpha2.GRPCRoute
GRPCRouteList = gatewayv1alpha2.GRPCRouteList
GRPCRouteMatch = gatewayv1alpha2.GRPCRouteMatch
GRPCRouteRule = gatewayv1alpha2.GRPCRouteRule
GRPCRouteSpec = gatewayv1alpha2.GRPCRouteSpec
GRPCRouteStatus = gatewayv1alpha2.GRPCRouteStatus
TCPRoute = gatewayv1alpha2.TCPRoute
TCPRouteList = gatewayv1alpha2.TCPRouteList
TCPRouteRule = gatewayv1alpha2.TCPRouteRule
TCPRouteSpec = gatewayv1alpha2.TCPRouteSpec
TCPRouteStatus = gatewayv1alpha2.TCPRouteStatus
TLSRoute = gatewayv1alpha2.TLSRoute
TLSRouteList = gatewayv1alpha2.TLSRouteList
TLSRouteRule = gatewayv1alpha2.TLSRouteRule
TLSRouteSpec = gatewayv1alpha2.TLSRouteSpec
TLSRouteStatus = gatewayv1alpha2.TLSRouteStatus
UDPRoute = gatewayv1alpha2.UDPRoute
UDPRouteList = gatewayv1alpha2.UDPRouteList
UDPRouteRule = gatewayv1alpha2.UDPRouteRule
UDPRouteSpec = gatewayv1alpha2.UDPRouteSpec
UDPRouteStatus = gatewayv1alpha2.UDPRouteStatus
GRPCBackendRef = gatewayv1alpha2.GRPCBackendRef
GRPCHeaderMatch = gatewayv1alpha2.GRPCHeaderMatch
GRPCHeaderName = gatewayv1alpha2.GRPCHeaderName
GRPCMethodMatch = gatewayv1alpha2.GRPCMethodMatch
GRPCMethodMatchType = gatewayv1alpha2.GRPCMethodMatchType
GRPCRoute = gatewayv1alpha2.GRPCRoute
GRPCRouteList = gatewayv1alpha2.GRPCRouteList
GRPCRouteMatch = gatewayv1alpha2.GRPCRouteMatch
GRPCRouteRule = gatewayv1alpha2.GRPCRouteRule
GRPCRouteSpec = gatewayv1alpha2.GRPCRouteSpec
GRPCRouteStatus = gatewayv1alpha2.GRPCRouteStatus
PolicyAncestorStatus = gatewayv1alpha2.PolicyAncestorStatus
TCPRoute = gatewayv1alpha2.TCPRoute
TCPRouteList = gatewayv1alpha2.TCPRouteList
TCPRouteRule = gatewayv1alpha2.TCPRouteRule
TCPRouteSpec = gatewayv1alpha2.TCPRouteSpec
TCPRouteStatus = gatewayv1alpha2.TCPRouteStatus
TLSRoute = gatewayv1alpha2.TLSRoute
TLSRouteList = gatewayv1alpha2.TLSRouteList
TLSRouteRule = gatewayv1alpha2.TLSRouteRule
TLSRouteSpec = gatewayv1alpha2.TLSRouteSpec
TLSRouteStatus = gatewayv1alpha2.TLSRouteStatus
UDPRoute = gatewayv1alpha2.UDPRoute
UDPRouteList = gatewayv1alpha2.UDPRouteList
UDPRouteRule = gatewayv1alpha2.UDPRouteRule
UDPRouteSpec = gatewayv1alpha2.UDPRouteSpec
UDPRouteStatus = gatewayv1alpha2.UDPRouteStatus
)

const (
Expand Down Expand Up @@ -164,4 +165,6 @@ const (

GRPCMethodMatchExact = gatewayv1alpha2.GRPCMethodMatchExact
GRPCMethodMatchRegularExpression = gatewayv1alpha2.GRPCMethodMatchRegularExpression
PolicyConditionAccepted = gatewayv1alpha2.PolicyConditionAccepted
PolicyReasonAccepted = gatewayv1alpha2.PolicyReasonAccepted
)
2 changes: 1 addition & 1 deletion pkg/apis/configuration/v1beta1/kongupstreampolicy_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ type KongUpstreamPolicy struct {
Spec KongUpstreamPolicySpec `json:"spec,omitempty"`

// Status defines the current state of KongUpstreamPolicy
Status gatewayv1alpha2.PolicyStatus
Status gatewayv1alpha2.PolicyStatus `json:"status,omitempty"`
}

// KongUpstreamPolicyList contains a list of KongUpstreamPolicy.
Expand Down
Loading

0 comments on commit 8f51be1

Please sign in to comment.