Skip to content

Commit edf3458

Browse files
committed
refacotr: apisixglobal
1 parent 1573729 commit edf3458

File tree

5 files changed

+43
-204
lines changed

5 files changed

+43
-204
lines changed

internal/controller/apisixconsumer_controller.go

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import (
1616
"context"
1717
"fmt"
1818

19-
"github.com/api7/gopkg/pkg/log"
2019
"github.com/go-logr/logr"
2120
corev1 "k8s.io/api/core/v1"
2221
networkingv1 "k8s.io/api/networking/v1"
@@ -30,7 +29,6 @@ import (
3029
"sigs.k8s.io/controller-runtime/pkg/handler"
3130
"sigs.k8s.io/controller-runtime/pkg/predicate"
3231
"sigs.k8s.io/controller-runtime/pkg/reconcile"
33-
gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
3432

3533
"github.com/apache/apisix-ingress-controller/api/v1alpha1"
3634
apiv2 "github.com/apache/apisix-ingress-controller/api/v2"
@@ -71,42 +69,33 @@ func (r *ApisixConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Reque
7169
return ctrl.Result{}, err
7270
}
7371

74-
tctx := provider.NewDefaultTranslateContext(ctx)
72+
var (
73+
tctx = provider.NewDefaultTranslateContext(ctx)
74+
err error
75+
)
76+
defer func() {
77+
r.updateStatus(ac, err)
78+
}()
7579

7680
ingressClass, err := GetIngressClass(tctx, r.Client, r.Log, ac.Spec.IngressClassName)
7781
if err != nil {
78-
log.Error(err, "failed to get IngressClass")
82+
r.Log.Error(err, "failed to get IngressClass")
7983
return ctrl.Result{}, err
8084
}
8185

8286
if err := ProcessIngressClassParameters(tctx, r.Client, r.Log, ac, ingressClass); err != nil {
83-
log.Error(err, "failed to process IngressClass parameters", "ingressClass", ingressClass.Name)
87+
r.Log.Error(err, "failed to process IngressClass parameters", "ingressClass", ingressClass.Name)
88+
return ctrl.Result{}, err
89+
}
90+
91+
if err := r.processSpec(ctx, tctx, ac); err != nil {
8492
return ctrl.Result{}, err
8593
}
8694

8795
if err := r.Provider.Update(ctx, tctx, ac); err != nil {
8896
r.Log.Error(err, "failed to update provider", "ApisixConsumer", ac)
89-
// Update status with failure condition
90-
r.updateStatus(ac, metav1.Condition{
91-
Type: string(apiv2.ConditionTypeAccepted),
92-
Status: metav1.ConditionFalse,
93-
ObservedGeneration: ac.Generation,
94-
LastTransitionTime: metav1.Now(),
95-
Reason: string(apiv2.ConditionReasonSyncFailed),
96-
Message: err.Error(),
97-
})
9897
return ctrl.Result{}, err
9998
}
100-
101-
// Update status with success condition
102-
r.updateStatus(ac, metav1.Condition{
103-
Type: string(gatewayv1.RouteConditionAccepted),
104-
Status: metav1.ConditionTrue,
105-
ObservedGeneration: ac.Generation,
106-
LastTransitionTime: metav1.Now(),
107-
Reason: string(gatewayv1.RouteReasonAccepted),
108-
Message: "The ApisixConsumer has been accepted by the apisix-ingress-controller",
109-
})
11099
return ctrl.Result{}, nil
111100
}
112101

@@ -210,7 +199,8 @@ func (r *ApisixConsumerReconciler) processSpec(ctx context.Context, tctx *provid
210199
return nil
211200
}
212201

213-
func (r *ApisixConsumerReconciler) updateStatus(consumer *apiv2.ApisixConsumer, condition metav1.Condition) {
202+
func (r *ApisixConsumerReconciler) updateStatus(consumer *apiv2.ApisixConsumer, err error) {
203+
SetApisixCRDConditionAccepted(&consumer.Status, consumer.GetGeneration(), err)
214204
r.Updater.Update(status.Update{
215205
NamespacedName: utils.NamespacedName(consumer),
216206
Resource: &apiv2.ApisixConsumer{},
@@ -221,7 +211,7 @@ func (r *ApisixConsumerReconciler) updateStatus(consumer *apiv2.ApisixConsumer,
221211
panic(err)
222212
}
223213
acCopy := ac.DeepCopy()
224-
acCopy.Status.Conditions = []metav1.Condition{condition}
214+
acCopy.Status = consumer.Status
225215
return acCopy
226216
}),
227217
})

internal/controller/apisixglobalrule_controller.go

Lines changed: 19 additions & 171 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,13 @@ package controller
1414

1515
import (
1616
"context"
17-
"errors"
1817
"fmt"
1918

2019
"github.com/api7/gopkg/pkg/log"
2120
"github.com/go-logr/logr"
22-
corev1 "k8s.io/api/core/v1"
2321
networkingv1 "k8s.io/api/networking/v1"
2422
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2523
"k8s.io/apimachinery/pkg/runtime"
26-
"k8s.io/apimachinery/pkg/types"
2724
ctrl "sigs.k8s.io/controller-runtime"
2825
"sigs.k8s.io/controller-runtime/pkg/builder"
2926
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -79,14 +76,14 @@ func (r *ApisixGlobalRuleReconciler) Reconcile(ctx context.Context, req ctrl.Req
7976
tctx := provider.NewDefaultTranslateContext(ctx)
8077

8178
// get the ingress class
82-
ingressClass, err := r.getIngressClass(&globalRule)
79+
ingressClass, err := GetIngressClass(tctx, r.Client, r.Log, globalRule.Spec.IngressClassName)
8380
if err != nil {
8481
log.Error(err, "failed to get IngressClass")
8582
return ctrl.Result{}, err
8683
}
8784

8885
// process IngressClass parameters if they reference GatewayProxy
89-
if err := r.processIngressClassParameters(ctx, tctx, &globalRule, ingressClass); err != nil {
86+
if err := ProcessIngressClassParameters(tctx, r.Client, r.Log, &globalRule, ingressClass); err != nil {
9087
log.Error(err, "failed to process IngressClass parameters", "ingressClass", ingressClass.Name)
9188
return ctrl.Result{}, err
9289
}
@@ -137,12 +134,13 @@ func (r *ApisixGlobalRuleReconciler) SetupWithManager(mgr ctrl.Manager) error {
137134
&networkingv1.IngressClass{},
138135
handler.EnqueueRequestsFromMapFunc(r.listGlobalRulesForIngressClass),
139136
builder.WithPredicates(
140-
predicate.NewPredicateFuncs(r.matchesIngressController),
137+
predicate.NewPredicateFuncs(matchesIngressController),
141138
),
142139
).
143140
Watches(&v1alpha1.GatewayProxy{},
144141
handler.EnqueueRequestsFromMapFunc(r.listGlobalRulesForGatewayProxy),
145142
).
143+
Named("apisixglobalrule").
146144
Complete(r)
147145
}
148146

@@ -187,181 +185,31 @@ func (r *ApisixGlobalRuleReconciler) matchesIngressClass(ingressClassName string
187185
return matchesController(ingressClass.Spec.Controller)
188186
}
189187

190-
// matchesIngressController check if the ingress class is controlled by us
191-
func (r *ApisixGlobalRuleReconciler) matchesIngressController(obj client.Object) bool {
192-
ingressClass, ok := obj.(*networkingv1.IngressClass)
193-
if !ok {
194-
return false
195-
}
196-
return matchesController(ingressClass.Spec.Controller)
197-
}
198-
199188
// listGlobalRulesForIngressClass list all global rules that use a specific ingress class
200189
func (r *ApisixGlobalRuleReconciler) listGlobalRulesForIngressClass(ctx context.Context, obj client.Object) []reconcile.Request {
201190
ingressClass, ok := obj.(*networkingv1.IngressClass)
202191
if !ok {
203192
return nil
204193
}
205194

206-
var requests []reconcile.Request
207-
208-
// List all global rules and filter based on ingress class
209-
globalRuleList := &apiv2.ApisixGlobalRuleList{}
210-
if err := r.List(ctx, globalRuleList); err != nil {
211-
r.Log.Error(err, "failed to list global rules")
212-
return nil
213-
}
214-
215-
isDefaultClass := IsDefaultIngressClass(ingressClass)
216-
for _, globalRule := range globalRuleList.Items {
217-
if (isDefaultClass && globalRule.Spec.IngressClassName == "") ||
218-
globalRule.Spec.IngressClassName == ingressClass.Name {
219-
requests = append(requests, reconcile.Request{
220-
NamespacedName: client.ObjectKey{
221-
Namespace: globalRule.Namespace,
222-
Name: globalRule.Name,
223-
},
224-
})
225-
}
226-
}
227-
228-
return requests
229-
}
230-
231-
// listGlobalRulesForGatewayProxy list all global rules that use a specific gateway proxy
232-
func (r *ApisixGlobalRuleReconciler) listGlobalRulesForGatewayProxy(ctx context.Context, obj client.Object) []reconcile.Request {
233-
gatewayProxy, ok := obj.(*v1alpha1.GatewayProxy)
234-
if !ok {
235-
return nil
236-
}
237-
238-
// Find all ingress classes that reference this gateway proxy
239-
ingressClassList := &networkingv1.IngressClassList{}
240-
if err := r.List(ctx, ingressClassList, client.MatchingFields{
241-
indexer.IngressClassParametersRef: indexer.GenIndexKey(gatewayProxy.GetNamespace(), gatewayProxy.GetName()),
242-
}); err != nil {
243-
r.Log.Error(err, "failed to list ingress classes for gateway proxy", "gatewayproxy", gatewayProxy.GetName())
244-
return nil
245-
}
246-
247-
var requests []reconcile.Request
248-
for _, ingressClass := range ingressClassList.Items {
249-
requests = append(requests, r.listGlobalRulesForIngressClass(ctx, &ingressClass)...)
250-
}
251-
252-
// Remove duplicates
253-
uniqueRequests := make(map[string]reconcile.Request)
254-
for _, request := range requests {
255-
uniqueRequests[request.String()] = request
256-
}
257-
258-
distinctRequests := make([]reconcile.Request, 0, len(uniqueRequests))
259-
for _, request := range uniqueRequests {
260-
distinctRequests = append(distinctRequests, request)
261-
}
262-
263-
return distinctRequests
264-
}
265-
266-
// getIngressClass get the ingress class for the global rule
267-
func (r *ApisixGlobalRuleReconciler) getIngressClass(globalRule *apiv2.ApisixGlobalRule) (*networkingv1.IngressClass, error) {
268-
if globalRule.Spec.IngressClassName == "" {
269-
// Check for default ingress class
270-
ingressClassList := &networkingv1.IngressClassList{}
271-
if err := r.List(context.Background(), ingressClassList, client.MatchingFields{
272-
indexer.IngressClass: config.GetControllerName(),
273-
}); err != nil {
274-
r.Log.Error(err, "failed to list ingress classes")
275-
return nil, err
276-
}
277-
278-
// Find the ingress class that is marked as default
279-
for _, ic := range ingressClassList.Items {
280-
if IsDefaultIngressClass(&ic) && matchesController(ic.Spec.Controller) {
281-
return &ic, nil
195+
return ListMatchingRequests(
196+
ctx,
197+
r.Client,
198+
r.Log,
199+
&apiv2.ApisixGlobalRuleList{},
200+
func(obj client.Object) bool {
201+
agr, ok := obj.(*apiv2.ApisixGlobalRule)
202+
if !ok {
203+
r.Log.Error(fmt.Errorf("expected ApisixGlobalRule, got %T", obj), "failed to match object type")
204+
return false
282205
}
283-
}
284-
log.Debugw("no default ingress class found")
285-
return nil, errors.New("no default ingress class found")
286-
}
287-
288-
// Check if the specified ingress class is controlled by us
289-
var ingressClass networkingv1.IngressClass
290-
if err := r.Get(context.Background(), client.ObjectKey{Name: globalRule.Spec.IngressClassName}, &ingressClass); err != nil {
291-
return nil, err
292-
}
293-
294-
if matchesController(ingressClass.Spec.Controller) {
295-
return &ingressClass, nil
296-
}
297-
298-
return nil, errors.New("ingress class is not controlled by us")
206+
return (IsDefaultIngressClass(ingressClass) && agr.Spec.IngressClassName == "") || agr.Spec.IngressClassName == ingressClass.Name
207+
},
208+
)
299209
}
300210

301-
// processIngressClassParameters processes the IngressClass parameters that reference GatewayProxy
302-
func (r *ApisixGlobalRuleReconciler) processIngressClassParameters(ctx context.Context, tctx *provider.TranslateContext, globalRule *apiv2.ApisixGlobalRule, ingressClass *networkingv1.IngressClass) error {
303-
if ingressClass == nil || ingressClass.Spec.Parameters == nil {
304-
return nil
305-
}
306-
307-
ingressClassKind := utils.NamespacedNameKind(ingressClass)
308-
globalRuleKind := utils.NamespacedNameKind(globalRule)
309-
310-
parameters := ingressClass.Spec.Parameters
311-
// check if the parameters reference GatewayProxy
312-
if parameters.APIGroup != nil && *parameters.APIGroup == v1alpha1.GroupVersion.Group && parameters.Kind == KindGatewayProxy {
313-
ns := globalRule.GetNamespace()
314-
if parameters.Namespace != nil {
315-
ns = *parameters.Namespace
316-
}
317-
318-
gatewayProxy := &v1alpha1.GatewayProxy{}
319-
if err := r.Get(ctx, client.ObjectKey{
320-
Namespace: ns,
321-
Name: parameters.Name,
322-
}, gatewayProxy); err != nil {
323-
r.Log.Error(err, "failed to get GatewayProxy", "namespace", ns, "name", parameters.Name)
324-
return err
325-
}
326-
327-
r.Log.Info("found GatewayProxy for IngressClass", "ingressClass", ingressClass.Name, "gatewayproxy", gatewayProxy.Name)
328-
tctx.GatewayProxies[ingressClassKind] = *gatewayProxy
329-
tctx.ResourceParentRefs[globalRuleKind] = append(tctx.ResourceParentRefs[globalRuleKind], ingressClassKind)
330-
331-
// check if the provider field references a secret
332-
if gatewayProxy.Spec.Provider != nil && gatewayProxy.Spec.Provider.Type == v1alpha1.ProviderTypeControlPlane {
333-
if gatewayProxy.Spec.Provider.ControlPlane != nil &&
334-
gatewayProxy.Spec.Provider.ControlPlane.Auth.Type == v1alpha1.AuthTypeAdminKey &&
335-
gatewayProxy.Spec.Provider.ControlPlane.Auth.AdminKey != nil &&
336-
gatewayProxy.Spec.Provider.ControlPlane.Auth.AdminKey.ValueFrom != nil &&
337-
gatewayProxy.Spec.Provider.ControlPlane.Auth.AdminKey.ValueFrom.SecretKeyRef != nil {
338-
339-
secretRef := gatewayProxy.Spec.Provider.ControlPlane.Auth.AdminKey.ValueFrom.SecretKeyRef
340-
secret := &corev1.Secret{}
341-
if err := r.Get(ctx, client.ObjectKey{
342-
Namespace: ns,
343-
Name: secretRef.Name,
344-
}, secret); err != nil {
345-
r.Log.Error(err, "failed to get secret for GatewayProxy provider",
346-
"namespace", ns,
347-
"name", secretRef.Name)
348-
return err
349-
}
350-
351-
r.Log.Info("found secret for GatewayProxy provider",
352-
"ingressClass", ingressClass.Name,
353-
"gatewayproxy", gatewayProxy.Name,
354-
"secret", secretRef.Name)
355-
356-
tctx.Secrets[types.NamespacedName{
357-
Namespace: ns,
358-
Name: secretRef.Name,
359-
}] = secret
360-
}
361-
}
362-
}
363-
364-
return nil
211+
func (r *ApisixGlobalRuleReconciler) listGlobalRulesForGatewayProxy(ctx context.Context, obj client.Object) []reconcile.Request {
212+
return listIngressClassRequestsForGatewayProxy(ctx, r.Client, obj, r.Log, r.listGlobalRulesForIngressClass)
365213
}
366214

367215
// updateStatus updates the ApisixGlobalRule status with the given condition

internal/provider/adc/translator/apisixconsumer.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ var (
4040
_hmacAuthEncodeURIParamsDefaultValue = true
4141
_hmacAuthValidateRequestBodyDefaultValue = false
4242
_hmacAuthMaxReqBodyDefaultValue = int64(524288)
43+
44+
_stringTrue = "true"
4345
)
4446

4547
func (t *Translator) TranslateApisixConsumer(tctx *provider.TranslateContext, ac *v2.ApisixConsumer) (*TranslateResult, error) {
@@ -197,7 +199,7 @@ func (t *Translator) translateConsumerJwtAuthPluginV2(tctx *provider.TranslateCo
197199
}
198200
base64SecretRaw := sec.Data["base64_secret"]
199201
var base64Secret bool
200-
if string(base64SecretRaw) == "true" {
202+
if string(base64SecretRaw) == _stringTrue {
201203
base64Secret = true
202204
}
203205
expRaw := sec.Data["exp"]
@@ -272,8 +274,8 @@ func (t *Translator) translateConsumerHMACAuthPluginV2(tctx *provider.TranslateC
272274
clockSkew = _hmacAuthClockSkewDefaultValue
273275
}
274276

275-
var signedHeaders []string
276277
signedHeadersRaw := sec.Data["signed_headers"]
278+
signedHeaders := make([]string, 0, len(signedHeadersRaw))
277279
for _, b := range signedHeadersRaw {
278280
signedHeaders = append(signedHeaders, string(b))
279281
}
@@ -283,7 +285,7 @@ func (t *Translator) translateConsumerHMACAuthPluginV2(tctx *provider.TranslateC
283285
if !ok {
284286
keepHeader = _hmacAuthKeepHeadersDefaultValue
285287
} else {
286-
if string(keepHeaderRaw) == "true" {
288+
if string(keepHeaderRaw) == _stringTrue {
287289
keepHeader = true
288290
} else {
289291
keepHeader = false
@@ -295,7 +297,7 @@ func (t *Translator) translateConsumerHMACAuthPluginV2(tctx *provider.TranslateC
295297
if !ok {
296298
encodeURIParams = _hmacAuthEncodeURIParamsDefaultValue
297299
} else {
298-
if string(encodeURIParamsRaw) == "true" {
300+
if string(encodeURIParamsRaw) == _stringTrue {
299301
encodeURIParams = true
300302
} else {
301303
encodeURIParams = false
@@ -307,7 +309,7 @@ func (t *Translator) translateConsumerHMACAuthPluginV2(tctx *provider.TranslateC
307309
if !ok {
308310
validateRequestBody = _hmacAuthValidateRequestBodyDefaultValue
309311
} else {
310-
if string(validateRequestBodyRaw) == "true" {
312+
if string(validateRequestBodyRaw) == _stringTrue {
311313
validateRequestBody = true
312314
} else {
313315
validateRequestBody = false

0 commit comments

Comments
 (0)