Skip to content

Commit 0da0b4a

Browse files
committed
manager status and test
1 parent 97e302b commit 0da0b4a

File tree

11 files changed

+158
-132
lines changed

11 files changed

+158
-132
lines changed

api/adc/types.go

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ type Upstream struct {
149149
HashOn string `json:"hash_on,omitempty" yaml:"hash_on,omitempty"`
150150
Key string `json:"key,omitempty" yaml:"key,omitempty"`
151151
Nodes UpstreamNodes `json:"nodes" yaml:"nodes"`
152-
PassHost *PassHost `json:"pass_host,omitempty" yaml:"pass_host,omitempty"`
152+
PassHost string `json:"pass_host,omitempty" yaml:"pass_host,omitempty"`
153153
Retries *int64 `json:"retries,omitempty" yaml:"retries,omitempty"`
154154
RetryTimeout *float64 `json:"retry_timeout,omitempty" yaml:"retry_timeout,omitempty"`
155155
Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"`
@@ -202,14 +202,6 @@ const (
202202
Trace Method = "TRACE"
203203
)
204204

205-
type PassHost string
206-
207-
const (
208-
Node PassHost = "node"
209-
Pass PassHost = "pass"
210-
Rewrite PassHost = "rewrite"
211-
)
212-
213205
type Scheme string
214206

215207
const (

api/v1alpha1/backendtrafficpolicy_types.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,11 @@ type BackendTrafficPolicySpec struct {
4444
//
4545
// +kubebuilder:validation:Enum=pass;node;rewrite;
4646
// +kubebuilder:default=pass
47-
PassHost string `json:"pass_host,omitempty" yaml:"pass_host,omitempty"`
47+
PassHost string `json:"passHost,omitempty" yaml:"passHost,omitempty"`
4848

4949
// Specifies the host of the Upstream request. This is only valid if
50-
// the pass_host is set to rewrite
51-
Host Hostname `json:"upstream_host,omitempty" yaml:"upstream_host,omitempty"`
50+
// the passHost is set to rewrite
51+
Host Hostname `json:"upstreamHost,omitempty" yaml:"upstreamHost,omitempty"`
5252
}
5353

5454
// LoadBalancer describes the load balancing parameters.

config/crd/bases/gateway.apisix.io_backendtrafficpolicies.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ spec:
7070
type: object
7171
x-kubernetes-validations:
7272
- rule: '!(has(self.key) && self.type != ''chash'')'
73-
pass_host:
73+
passHost:
7474
default: pass
7575
description: |-
7676
Configures the host when the request is forwarded to the upstream.
@@ -175,10 +175,10 @@ spec:
175175
pattern: ^[0-9]+s$
176176
type: string
177177
type: object
178-
upstream_host:
178+
upstreamHost:
179179
description: |-
180180
Specifies the host of the Upstream request. This is only valid if
181-
the pass_host is set to rewrite
181+
the passHost is set to rewrite
182182
maxLength: 253
183183
minLength: 1
184184
pattern: ^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$

internal/controller/httproute_controller.go

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ func (r *HTTPRouteReconciler) SetupWithManager(mgr ctrl.Manager) error {
129129
}
130130

131131
func (r *HTTPRouteReconciler) listHTTPRouteForGenericEvent(ctx context.Context, obj client.Object) []reconcile.Request {
132+
var namespacedNameMap = make(map[types.NamespacedName]struct{})
132133
requests := []reconcile.Request{}
133134
switch v := obj.(type) {
134135
case *v1alpha1.BackendTrafficPolicy:
@@ -144,12 +145,19 @@ func (r *HTTPRouteReconciler) listHTTPRouteForGenericEvent(ctx context.Context,
144145
httprouteAll = append(httprouteAll, httprouteList.Items...)
145146
}
146147
for _, hr := range httprouteAll {
147-
requests = append(requests, reconcile.Request{
148-
NamespacedName: client.ObjectKey{
149-
Namespace: hr.Namespace,
150-
Name: hr.Name,
151-
},
152-
})
148+
key := types.NamespacedName{
149+
Namespace: hr.Namespace,
150+
Name: hr.Name,
151+
}
152+
if _, ok := namespacedNameMap[key]; !ok {
153+
namespacedNameMap[key] = struct{}{}
154+
requests = append(requests, reconcile.Request{
155+
NamespacedName: client.ObjectKey{
156+
Namespace: hr.Namespace,
157+
Name: hr.Name,
158+
},
159+
})
160+
}
153161
}
154162
default:
155163
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to BackendTrafficPolicy")
@@ -203,6 +211,8 @@ func (r *HTTPRouteReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
203211

204212
tctx := provider.NewDefaultTranslateContext(ctx)
205213

214+
tctx.RouteParentRefs = hr.Spec.ParentRefs
215+
206216
if err := r.processHTTPRoute(tctx, hr); err != nil {
207217
acceptStatus.status = false
208218
acceptStatus.msg = err.Error()
@@ -328,19 +338,22 @@ func (r *HTTPRouteReconciler) listHTTPRoutesForBackendTrafficPolicy(ctx context.
328338
}
329339
httprouteList = append(httprouteList, hrList.Items...)
330340
}
331-
341+
var namespacedNameMap = make(map[types.NamespacedName]struct{})
332342
requests := make([]reconcile.Request, 0, len(httprouteList))
333343
for _, hr := range httprouteList {
334-
requests = append(requests, reconcile.Request{
335-
NamespacedName: client.ObjectKey{
336-
Namespace: hr.Namespace,
337-
Name: hr.Name,
338-
},
339-
})
340-
}
341-
if !policy.GetDeletionTimestamp().IsZero() {
342-
// If the policy is deleted, we need to list all HTTPRoutes that reference this policy
343-
// and add them to the requests.
344+
key := types.NamespacedName{
345+
Namespace: hr.Namespace,
346+
Name: hr.Name,
347+
}
348+
if _, ok := namespacedNameMap[key]; !ok {
349+
namespacedNameMap[key] = struct{}{}
350+
requests = append(requests, reconcile.Request{
351+
NamespacedName: client.ObjectKey{
352+
Namespace: hr.Namespace,
353+
Name: hr.Name,
354+
},
355+
})
356+
}
344357
}
345358
return requests
346359
}

internal/controller/indexer/indexer.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,9 @@ func SetupIndexer(mgr ctrl.Manager) error {
3737
if err := setupConsumerIndexer(mgr); err != nil {
3838
return err
3939
}
40-
/*
41-
if err := setupBackendTrafficPolicyIndexer(mgr); err != nil {
42-
return err
43-
}
44-
*/
40+
if err := setupBackendTrafficPolicyIndexer(mgr); err != nil {
41+
return err
42+
}
4543
return nil
4644
}
4745

@@ -192,7 +190,7 @@ func setupIngressIndexer(mgr ctrl.Manager) error {
192190
return nil
193191
}
194192

195-
func SetupBackendTrafficPolicyIndexer(mgr ctrl.Manager) error {
193+
func setupBackendTrafficPolicyIndexer(mgr ctrl.Manager) error {
196194
if err := mgr.GetFieldIndexer().IndexField(
197195
context.Background(),
198196
&v1alpha1.BackendTrafficPolicy{},

internal/controller/policies.go

Lines changed: 64 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package controller
33
import (
44
"fmt"
55

6+
"k8s.io/utils/ptr"
67
gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
78
gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
89

@@ -11,6 +12,7 @@ import (
1112
"github.com/api7/api7-ingress-controller/internal/controller/indexer"
1213
"github.com/api7/api7-ingress-controller/internal/provider"
1314
"github.com/go-logr/logr"
15+
"k8s.io/apimachinery/pkg/api/meta"
1416
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1517
"k8s.io/apimachinery/pkg/runtime/schema"
1618
"k8s.io/apimachinery/pkg/types"
@@ -26,10 +28,14 @@ func (p PolicyTargetKey) String() string {
2628
return p.NsName.String() + "/" + p.GroupKind.String()
2729
}
2830

29-
func ProcessBackendTrafficPolicy(c client.Client,
31+
func ProcessBackendTrafficPolicy(
32+
c client.Client,
3033
log logr.Logger,
31-
tctx *provider.TranslateContext) {
32-
conflicts := map[string]v1alpha1.BackendTrafficPolicy{}
34+
tctx *provider.TranslateContext,
35+
) {
36+
conflicts := map[string]*v1alpha1.BackendTrafficPolicy{}
37+
servicePortNameMap := map[string]bool{}
38+
policyMap := map[types.NamespacedName]*v1alpha1.BackendTrafficPolicy{}
3339
for _, service := range tctx.Services {
3440
backendTrafficPolicyList := &v1alpha1.BackendTrafficPolicyList{}
3541
if err := c.List(tctx, backendTrafficPolicyList,
@@ -43,58 +49,61 @@ func ProcessBackendTrafficPolicy(c client.Client,
4349
if len(backendTrafficPolicyList.Items) == 0 {
4450
continue
4551
}
46-
47-
portNameExist := make(map[string]bool, len(service.Spec.Ports))
4852
for _, port := range service.Spec.Ports {
49-
portNameExist[port.Name] = true
53+
key := fmt.Sprintf("%s/%s/%s", service.Namespace, service.Name, port.Name)
54+
servicePortNameMap[key] = true
55+
}
56+
57+
for _, p := range backendTrafficPolicyList.Items {
58+
policyMap[types.NamespacedName{
59+
Name: p.Name,
60+
Namespace: p.Namespace,
61+
}] = p.DeepCopy()
5062
}
51-
for _, policy := range backendTrafficPolicyList.Items {
52-
targetRefs := policy.Spec.TargetRefs
53-
updated := false
54-
for _, targetRef := range targetRefs {
55-
sectionName := targetRef.SectionName
56-
key := PolicyTargetKey{
57-
NsName: types.NamespacedName{Namespace: service.Namespace, Name: service.Name},
58-
GroupKind: schema.GroupKind{Group: "", Kind: "Service"},
59-
}
60-
condition := NewPolicyCondition(policy.Generation, true, "Policy has been accepted")
61-
if sectionName != nil && !portNameExist[string(*sectionName)] {
62-
condition = NewPolicyCondition(policy.Generation, false, fmt.Sprintf("SectionName %s not found in Service %s/%s", *sectionName, service.Namespace, service.Name))
63-
processPolicyStatus(&policy, tctx, condition, &updated)
64-
continue
65-
}
66-
if p, ok := conflicts[key.String()]; ok && (p.Name == policy.Name && p.Namespace == policy.Namespace) {
67-
condition = NewPolicyConflictCondition(policy.Generation, fmt.Sprintf("Unable to target Service %s/%s, because it conflicts with another BackendTrafficPolicy", service.Namespace, service.Name))
68-
processPolicyStatus(&policy, tctx, condition, &updated)
69-
continue
70-
}
71-
conflicts[key.String()] = policy
72-
processPolicyStatus(&policy, tctx, condition, &updated)
63+
}
64+
65+
for _, p := range policyMap {
66+
policy := p.DeepCopy()
67+
targetRefs := policy.Spec.TargetRefs
68+
updated := false
69+
for _, targetRef := range targetRefs {
70+
sectionName := targetRef.SectionName
71+
key := PolicyTargetKey{
72+
NsName: types.NamespacedName{Namespace: p.GetNamespace(), Name: string(targetRef.Name)},
73+
GroupKind: schema.GroupKind{Group: "", Kind: "Service"},
7374
}
74-
if _, ok := tctx.BackendTrafficPolicies[types.NamespacedName{
75-
Name: policy.Name,
76-
Namespace: policy.Namespace,
77-
}]; ok {
75+
condition := NewPolicyCondition(policy.Generation, true, "Policy has been accepted")
76+
if sectionName != nil && !servicePortNameMap[fmt.Sprintf("%s/%s/%s", policy.Namespace, string(targetRef.Name), *sectionName)] {
77+
condition = NewPolicyCondition(policy.Generation, false, fmt.Sprintf("No section name %s found in Service %s/%s", *sectionName, policy.Namespace, targetRef.Name))
78+
processPolicyStatus(policy, tctx, condition, &updated)
7879
continue
7980
}
80-
81-
if updated {
82-
tctx.StatusUpdaters = append(tctx.StatusUpdaters, policy.DeepCopy())
81+
if _, ok := conflicts[key.String()]; ok {
82+
condition = NewPolicyConflictCondition(policy.Generation, fmt.Sprintf("Unable to target Service %s/%s, because it conflicts with another BackendTrafficPolicy", policy.Namespace, targetRef.Name))
83+
processPolicyStatus(policy, tctx, condition, &updated)
84+
continue
8385
}
84-
85-
tctx.BackendTrafficPolicies[types.NamespacedName{
86-
Name: policy.Name,
87-
Namespace: policy.Namespace,
88-
}] = policy.DeepCopy()
86+
conflicts[key.String()] = policy
87+
processPolicyStatus(policy, tctx, condition, &updated)
88+
}
89+
if updated {
90+
tctx.StatusUpdaters = append(tctx.StatusUpdaters, policy.DeepCopy())
8991
}
9092
}
93+
for _, policy := range conflicts {
94+
tctx.BackendTrafficPolicies[types.NamespacedName{
95+
Name: policy.Name,
96+
Namespace: policy.Namespace,
97+
}] = policy
98+
}
9199
}
92100

93101
func processPolicyStatus(policy *v1alpha1.BackendTrafficPolicy,
94102
tctx *provider.TranslateContext,
95103
condition metav1.Condition,
96-
updated *bool) {
97-
if ok := SetAncestors(&policy.Status, tctx.ParentRefs, condition); ok {
104+
updated *bool,
105+
) {
106+
if ok := SetAncestors(&policy.Status, tctx.RouteParentRefs, condition); ok {
98107
*updated = true
99108
}
100109
}
@@ -115,17 +124,21 @@ func SetAncestors(status *v1alpha1.PolicyStatus, parentRefs []gatewayv1.ParentRe
115124
}
116125

117126
func SetAncestorStatus(status *v1alpha1.PolicyStatus, ancestorStatus gatewayv1alpha2.PolicyAncestorStatus) bool {
127+
if len(ancestorStatus.Conditions) == 0 {
128+
return false
129+
}
130+
condition := ancestorStatus.Conditions[0]
118131
for _, c := range status.Ancestors {
119-
if c.AncestorRef == ancestorStatus.AncestorRef {
120-
if len(c.Conditions) == 0 || len(ancestorStatus.Conditions) == 0 {
121-
c.Conditions = ancestorStatus.Conditions
122-
return true
123-
}
124-
if c.Conditions[0].ObservedGeneration < ancestorStatus.Conditions[0].ObservedGeneration {
125-
c.Conditions = ancestorStatus.Conditions
126-
return true
132+
if c.AncestorRef.Name == ancestorStatus.AncestorRef.Name &&
133+
ptr.Equal(c.AncestorRef.Namespace, ancestorStatus.AncestorRef.Namespace) &&
134+
ptr.Equal(c.AncestorRef.Group, ancestorStatus.AncestorRef.Group) &&
135+
ptr.Equal(c.AncestorRef.Kind, ancestorStatus.AncestorRef.Kind) &&
136+
c.ControllerName == ancestorStatus.ControllerName {
137+
if !VerifyConditions(&c.Conditions, condition) {
138+
return false
127139
}
128-
return false
140+
meta.SetStatusCondition(&c.Conditions, condition)
141+
return true
129142
}
130143
}
131144
status.Ancestors = append(status.Ancestors, ancestorStatus)

internal/controller/status.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ func NewPolicyCondition(observedGeneration int64, status bool, message string) m
6363
Status: conditionStatus,
6464
Message: message,
6565
ObservedGeneration: observedGeneration,
66+
LastTransitionTime: metav1.Now(),
6667
}
6768
}
6869

@@ -73,6 +74,7 @@ func NewPolicyConflictCondition(observedGeneration int64, message string) metav1
7374
Status: metav1.ConditionFalse,
7475
Message: message,
7576
ObservedGeneration: observedGeneration,
77+
LastTransitionTime: metav1.Now(),
7678
}
7779
}
7880

@@ -82,9 +84,6 @@ func UpdateStatus(
8284
tctx *provider.TranslateContext,
8385
) {
8486
for _, obj := range tctx.StatusUpdaters {
85-
if err := c.Status().Update(tctx, obj); err != nil {
86-
log.Error(err, "failed to update status", "object", obj)
87-
continue
88-
}
87+
_ = c.Status().Update(tctx, obj)
8988
}
9089
}

internal/provider/adc/translator/policies.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ func (t *Translator) attachBackendTrafficPolicyToUpstream(policy *v1alpha1.Backe
3333
if policy == nil {
3434
return
3535
}
36+
upstream.PassHost = policy.Spec.PassHost
3637
upstream.UpstreamHost = string(policy.Spec.Host)
3738
upstream.Scheme = policy.Spec.Scheme
3839
if policy.Spec.Retries != nil {

internal/provider/provider.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ type Provider interface {
1919

2020
type TranslateContext struct {
2121
context.Context
22-
ParentRefs []gatewayv1.ParentReference
22+
RouteParentRefs []gatewayv1.ParentReference
2323
BackendRefs []gatewayv1.BackendRef
2424
GatewayTLSConfig []gatewayv1.GatewayTLSConfig
2525
GatewayProxy *v1alpha1.GatewayProxy

0 commit comments

Comments
 (0)