Skip to content

Commit bd81b5a

Browse files
committed
Refactor GatewayClass protection logic to use indexer
Simplify the GatewayClass deletion protection by leveraging an indexer to filter Gateways. This improves efficiency and readability by reducing unnecessary iterations and directly querying relevant resources.
1 parent 057377e commit bd81b5a

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

internal/controller/gatewayclass_congroller.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
1818

1919
"github.com/api7/api7-ingress-controller/internal/controller/config"
20+
"github.com/api7/api7-ingress-controller/internal/controller/indexer"
2021
)
2122

2223
const (
@@ -61,20 +62,18 @@ func (r *GatewayClassReconciler) Reconcile(ctx context.Context, req ctrl.Request
6162
} else {
6263
if controllerutil.ContainsFinalizer(gc, FinalizerGatewayClassProtection) {
6364
var gatewayList gatewayv1.GatewayList
64-
if err := r.List(ctx, &gatewayList); err != nil {
65+
if err := r.List(ctx, &gatewayList, client.MatchingFields{indexer.GatewayClassIndexRef: gc.Name}); err != nil {
6566
r.Log.Error(err, "failed to list gateways")
6667
return ctrl.Result{}, err
6768
}
68-
var gateways []types.NamespacedName
69-
for _, gateway := range gatewayList.Items {
70-
if string(gateway.Spec.GatewayClassName) == gc.GetName() {
69+
if len(gatewayList.Items) > 0 {
70+
var gateways []types.NamespacedName
71+
for _, item := range gatewayList.Items {
7172
gateways = append(gateways, types.NamespacedName{
72-
Namespace: gateway.GetNamespace(),
73-
Name: gateway.GetName(),
73+
Namespace: item.GetNamespace(),
74+
Name: item.GetName(),
7475
})
7576
}
76-
}
77-
if len(gateways) > 0 {
7877
r.Eventf(gc, "Warning", "DeletionBlocked", "the GatewayClass is still used by Gateways: %v", gateways)
7978
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
8079
} else {

0 commit comments

Comments
 (0)