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

Gateway API: Implement generic route checks #25885

Merged
merged 1 commit into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion operator/pkg/gateway-api/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func getGatewaysForSecret(ctx context.Context, c client.Client, obj client.Objec
}

for _, cert := range l.TLS.CertificateRefs {
if !IsSecret(cert) {
if !helpers.IsSecret(cert) {
continue
}
ns := helpers.NamespaceDerefOr(cert.Namespace, gw.GetNamespace())
Expand Down
2 changes: 1 addition & 1 deletion operator/pkg/gateway-api/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func getReconcileRequestsForRoute(ctx context.Context, c client.Client, object m
})

for _, parent := range route.ParentRefs {
if !IsGateway(parent) {
if !helpers.IsGateway(parent) {
continue
}

Expand Down
2 changes: 1 addition & 1 deletion operator/pkg/gateway-api/gateway_reconcile.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ func (r *gatewayReconciler) setListenerStatus(ctx context.Context, gw *gatewayv1

if l.TLS != nil {
for _, cert := range l.TLS.CertificateRefs {
if !IsSecret(cert) {
if !helpers.IsSecret(cert) {
conds = merge(conds, metav1.Condition{
Type: string(gatewayv1beta1.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
Expand Down
12 changes: 0 additions & 12 deletions operator/pkg/gateway-api/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,6 @@ const (
kindSecret = "Secret"
)

func IsGateway(parent gatewayv1beta1.ParentReference) bool {
return (parent.Kind == nil || *parent.Kind == kindGateway) && (parent.Group == nil || *parent.Group == gatewayv1beta1.GroupName)
}

func IsService(be gatewayv1beta1.BackendObjectReference) bool {
return (be.Kind == nil || *be.Kind == kindService) && (be.Group == nil || *be.Group == corev1.GroupName)
}

func IsSecret(secret gatewayv1beta1.SecretObjectReference) bool {
return (secret.Kind == nil || *secret.Kind == kindSecret) && (secret.Group == nil || *secret.Group == corev1.GroupName)
}

func GatewayAddressTypePtr(addr gatewayv1beta1.AddressType) *gatewayv1beta1.AddressType {
return &addr
}
Expand Down
27 changes: 27 additions & 0 deletions operator/pkg/gateway-api/helpers/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium

package helpers

import (
corev1 "k8s.io/api/core/v1"
gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1"
)

const (
kindGateway = "Gateway"
kindService = "Service"
kindSecret = "Secret"
)

func IsGateway(parent gatewayv1beta1.ParentReference) bool {
return (parent.Kind == nil || *parent.Kind == kindGateway) && (parent.Group == nil || *parent.Group == gatewayv1beta1.GroupName)
}

func IsService(be gatewayv1beta1.BackendObjectReference) bool {
return (be.Kind == nil || *be.Kind == kindService) && (be.Group == nil || *be.Group == corev1.GroupName)
}

func IsSecret(secret gatewayv1beta1.SecretObjectReference) bool {
return (secret.Kind == nil || *secret.Kind == kindSecret) && (secret.Group == nil || *secret.Group == corev1.GroupName)
}
6 changes: 2 additions & 4 deletions operator/pkg/gateway-api/httproute.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ const (
gatewayIndex = "gatewayIndex"
)

type httpRouteChecker func(ctx context.Context, client client.Client, grants *gatewayv1beta1.ReferenceGrantList, hr *gatewayv1beta1.HTTPRoute) (ctrl.Result, error)

// httpRouteReconciler reconciles a HTTPRoute object
type httpRouteReconciler struct {
client.Client
Expand All @@ -49,7 +47,7 @@ func (r *httpRouteReconciler) SetupWithManager(mgr ctrl.Manager) error {
var backendServices []string
for _, rule := range hr.Spec.Rules {
for _, backend := range rule.BackendRefs {
if !IsService(backend.BackendObjectReference) {
if !helpers.IsService(backend.BackendObjectReference) {
continue
}
backendServices = append(backendServices,
Expand All @@ -71,7 +69,7 @@ func (r *httpRouteReconciler) SetupWithManager(mgr ctrl.Manager) error {
hr := rawObj.(*gatewayv1beta1.HTTPRoute)
var gateways []string
for _, parent := range hr.Spec.ParentRefs {
if !IsGateway(parent) {
if !helpers.IsGateway(parent) {
continue
}
gateways = append(gateways,
Expand Down
189 changes: 46 additions & 143 deletions operator/pkg/gateway-api/httproute_reconcile.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1"

"github.com/cilium/cilium/operator/pkg/gateway-api/helpers"
"github.com/cilium/cilium/operator/pkg/gateway-api/routechecks"
"github.com/cilium/cilium/pkg/logging/logfields"
)

Expand Down Expand Up @@ -61,159 +59,64 @@ func (r *httpRouteReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
return fail(fmt.Errorf("failed to retrieve reference grants: %w", err))
}

for _, fn := range []httpRouteChecker{
validateService,
validateGateway,
} {
if res, err := fn(ctx, r.Client, grants, hr); err != nil {
return res, err
}
// input for the validators
i := &routechecks.HTTPRouteInput{
Ctx: ctx,
Logger: scopedLog.WithField(logfields.Resource, hr),
Client: r.Client,
Grants: grants,
HTTPRoute: hr,
}

scopedLog.Info("Successfully reconciled HTTPRoute")
return success()
}

func validateService(ctx context.Context, c client.Client, grants *gatewayv1beta1.ReferenceGrantList, hr *gatewayv1beta1.HTTPRoute) (ctrl.Result, error) {
scopedLog := log.WithContext(ctx).WithFields(logrus.Fields{
logfields.Controller: "httpRoute",
logfields.Resource: client.ObjectKeyFromObject(hr),
})

for _, rule := range hr.Spec.Rules {
for _, be := range rule.BackendRefs {
ns := helpers.NamespaceDerefOr(be.Namespace, hr.GetNamespace())

if ns != hr.GetNamespace() && !helpers.IsBackendReferenceAllowed(hr.GetNamespace(), be.BackendRef, gatewayv1beta1.SchemeGroupVersion.WithKind("HTTPRoute"), grants.Items) {
// no reference grants, update the status for all the parents
for _, parent := range hr.Spec.ParentRefs {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpRefNotPermittedRouteCondition(hr, "Cross namespace references are not allowed"),
})
}

return success()
}

if !IsService(be.BackendObjectReference) {
for _, parent := range hr.Spec.ParentRefs {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpInvalidKindRouteCondition(hr, string("Unsupported backend kind "+*be.Kind)),
})
}
return success()
}

svc := &corev1.Service{}
if err := c.Get(ctx, client.ObjectKey{Namespace: ns, Name: string(be.Name)}, svc); err != nil {
if !k8serrors.IsNotFound(err) {
scopedLog.WithError(err).Error("Failed to get Service")
return fail(err)
}
// Service does not exist, update the status for all the parents
// The `Accepted` condition on a route only describes whether
// the route attached successfully to its parent, so no error
// is returned here, so that the next validation can be run.
for _, parent := range hr.Spec.ParentRefs {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpBackendNotFoundRouteCondition(hr, err.Error()),
})
}
return success()
}

// Service exists, update the status for all the parents
for _, parent := range hr.Spec.ParentRefs {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpRouteResolvedRefsOkayCondition(hr, "Service reference is valid"),
})
}
}
}
return success()
}

func validateGateway(ctx context.Context, c client.Client, _ *gatewayv1beta1.ReferenceGrantList, hr *gatewayv1beta1.HTTPRoute) (ctrl.Result, error) {
scopedLog := log.WithContext(ctx).WithFields(logrus.Fields{
logfields.Controller: "httpRoute",
logfields.Resource: client.ObjectKeyFromObject(hr),
})

// gateway validators
for _, parent := range hr.Spec.ParentRefs {
ns := helpers.NamespaceDerefOr(parent.Namespace, hr.GetNamespace())
gw := &gatewayv1beta1.Gateway{}
if err := c.Get(ctx, client.ObjectKey{Namespace: ns, Name: string(parent.Name)}, gw); err != nil {
if !k8serrors.IsNotFound(err) {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpRouteAcceptedCondition(hr, false, err.Error()),
})
return fail(err)
}
// Gateway does not exist, update the status for this HTTPRoute
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpRouteAcceptedCondition(hr, false, err.Error()),
})
continue
}

if !hasMatchingController(ctx, c, controllerName)(gw) {
continue
}
// set acceptance to okay, this wil be overwritten in checks if needed
i.SetParentCondition(parent, metav1.Condition{
Type: conditionStatusAccepted,
Status: metav1.ConditionTrue,
Reason: conditionReasonAccepted,
Message: "Accepted HTTPRoute",
})

if !isAllowed(ctx, c, gw, hr) {
// Gateway is not attachable, update the status for this HTTPRoute
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpRouteNotAllowedByListenersCondition(hr, "HTTPRoute is not allowed"),
})
continue
}
// set status to okay, this wil be overwritten in checks if needed
i.SetAllParentCondition(metav1.Condition{
Type: string(gatewayv1beta1.RouteConditionResolvedRefs),
Status: metav1.ConditionTrue,
Reason: string(gatewayv1beta1.RouteReasonResolvedRefs),
Message: "Service reference is valid",
})

if parent.Port != nil {
found := false
for _, listener := range gw.Spec.Listeners {
if listener.Port == *parent.Port {
found = true
break
}
}
if !found {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpNoMatchingParentCondition(hr, fmt.Sprintf("No matching listener with port %d", *parent.Port)),
})
continue
// run the actual validators
for _, fn := range []routechecks.CheckGatewayFunc{
routechecks.CheckGatewayAllowedForNamespace,
routechecks.CheckGatewayRouteKindAllowed,
routechecks.CheckGatewayMatchingPorts,
routechecks.CheckGatewayMatchingHostnames,
routechecks.CheckGatewayMatchingSection,
} {
continueCheck, err := fn(i, parent)
if err != nil {
return ctrl.Result{}, err
}
}

if parent.SectionName != nil {
found := false
for _, listener := range gw.Spec.Listeners {
if listener.Name == *parent.SectionName {
found = true
break
}
}
if !found {
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpNoMatchingParentCondition(hr, fmt.Sprintf("No matching listener with sectionName %s", *parent.SectionName)),
})
continue
if !continueCheck {
break
}
}
}

if len(computeHosts(gw, hr.Spec.Hostnames)) == 0 {
// No matching host, update the status for this HTTPRoute
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpNoMatchingListenerHostnameRouteCondition(hr, "No matching listener hostname"),
})
continue
for _, fn := range []routechecks.CheckRuleFunc{
routechecks.CheckAgainstCrossNamespaceBackendReferences,
routechecks.CheckBackendIsService,
routechecks.CheckBackendIsExistingService,
} {
if continueCheck, err := fn(i); err != nil || !continueCheck {
return ctrl.Result{}, err
}

scopedLog.Debug("HTTPRoute is attachable")
// Gateway is attachable, update the status for this HTTPRoute
mergeHTTPRouteStatusConditions(hr, parent, []metav1.Condition{
httpRouteAcceptedCondition(hr, true, httpRouteAcceptedMessage),
})
}

scopedLog.Info("Successfully reconciled HTTPRoute")
return success()
}

Expand Down