-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhttproute_controller.go
More file actions
353 lines (316 loc) · 9.9 KB
/
httproute_controller.go
File metadata and controls
353 lines (316 loc) · 9.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package controller
import (
"context"
"fmt"
"strings"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
discoveryv1 "k8s.io/api/discovery/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
"github.com/api7/api7-ingress-controller/api/v1alpha1"
"github.com/api7/api7-ingress-controller/internal/controller/indexer"
"github.com/api7/api7-ingress-controller/internal/provider"
)
// HTTPRouteReconciler reconciles a GatewayClass object.
type HTTPRouteReconciler struct { //nolint:revive
client.Client
Scheme *runtime.Scheme
Log logr.Logger
Provider provider.Provider
}
// SetupWithManager sets up the controller with the Manager.
func (r *HTTPRouteReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&gatewayv1.HTTPRoute{}).
WithEventFilter(predicate.GenerationChangedPredicate{}).
Watches(&discoveryv1.EndpointSlice{},
handler.EnqueueRequestsFromMapFunc(r.listHTTPRoutesByServiceBef),
).
Watches(&v1alpha1.PluginConfig{},
handler.EnqueueRequestsFromMapFunc(r.listHTTPRoutesByExtensionRef),
).
Watches(&gatewayv1.Gateway{},
handler.EnqueueRequestsFromMapFunc(r.listHTTPRoutesForGateway),
builder.WithPredicates(
predicate.Funcs{
GenericFunc: func(e event.GenericEvent) bool {
return false
},
DeleteFunc: func(e event.DeleteEvent) bool {
return false
},
CreateFunc: func(e event.CreateEvent) bool {
return true
},
UpdateFunc: func(e event.UpdateEvent) bool {
return true
},
},
),
).
Complete(r)
}
func (r *HTTPRouteReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
hr := new(gatewayv1.HTTPRoute)
if err := r.Get(ctx, req.NamespacedName, hr); err != nil {
if client.IgnoreNotFound(err) == nil {
hr.Namespace = req.Namespace
hr.Name = req.Name
hr.TypeMeta = metav1.TypeMeta{
Kind: KindHTTPRoute,
APIVersion: gatewayv1.GroupVersion.String(),
}
if err := r.Provider.Delete(ctx, hr); err != nil {
r.Log.Error(err, "failed to delete httproute", "httproute", hr)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
type status struct {
status bool
msg string
}
resolveRefStatus := status{
status: true,
msg: "backendRefs are resolved",
}
acceptStatus := status{
status: true,
msg: "Route is accepted",
}
gateways, err := ParseRouteParentRefs(ctx, r.Client, hr, hr.Spec.ParentRefs)
if err != nil {
return ctrl.Result{}, err
}
if len(gateways) == 0 {
return ctrl.Result{}, nil
}
tctx := provider.NewDefaultTranslateContext()
for _, gateway := range gateways {
if err := ProcessGatewayProxy(r.Client, tctx, gateway.Gateway); err != nil {
acceptStatus.status = false
acceptStatus.msg = err.Error()
}
}
if err := r.processHTTPRoute(tctx, hr); err != nil {
acceptStatus.status = false
acceptStatus.msg = err.Error()
}
if err := r.processHTTPRouteBackendRefs(tctx); err != nil {
resolveRefStatus = status{
status: false,
msg: err.Error(),
}
}
if err := r.Provider.Update(ctx, tctx, hr); err != nil {
acceptStatus.status = false
acceptStatus.msg = err.Error()
}
// TODO: diff the old and new status
hr.Status.Parents = make([]gatewayv1.RouteParentStatus, 0, len(gateways))
for _, gateway := range gateways {
parentStatus := gatewayv1.RouteParentStatus{}
SetRouteParentRef(&parentStatus, gateway.Gateway.Name, gateway.Gateway.Namespace)
for _, condition := range gateway.Conditions {
parentStatus.Conditions = MergeCondition(parentStatus.Conditions, condition)
}
if gateway.ListenerName == "" {
continue
}
SetRouteConditionAccepted(&parentStatus, hr.GetGeneration(), acceptStatus.status, acceptStatus.msg)
SetRouteConditionResolvedRefs(&parentStatus, hr.GetGeneration(), resolveRefStatus.status, resolveRefStatus.msg)
hr.Status.Parents = append(hr.Status.Parents, parentStatus)
}
if err := r.Status().Update(ctx, hr); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *HTTPRouteReconciler) listHTTPRoutesByServiceBef(ctx context.Context, obj client.Object) []reconcile.Request {
endpointSlice, ok := obj.(*discoveryv1.EndpointSlice)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to EndpointSlice")
return nil
}
namespace := endpointSlice.GetNamespace()
serviceName := endpointSlice.Labels[discoveryv1.LabelServiceName]
hrList := &gatewayv1.HTTPRouteList{}
if err := r.List(ctx, hrList, client.MatchingFields{
indexer.ServiceIndexRef: indexer.GenIndexKey(namespace, serviceName),
}); err != nil {
r.Log.Error(err, "failed to list httproutes by service", "service", serviceName)
return nil
}
requests := make([]reconcile.Request, 0, len(hrList.Items))
for _, hr := range hrList.Items {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: hr.Namespace,
Name: hr.Name,
},
})
}
return requests
}
func (r *HTTPRouteReconciler) listHTTPRoutesByExtensionRef(ctx context.Context, obj client.Object) []reconcile.Request {
pluginconfig, ok := obj.(*v1alpha1.PluginConfig)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to EndpointSlice")
return nil
}
namespace := pluginconfig.GetNamespace()
name := pluginconfig.GetName()
hrList := &gatewayv1.HTTPRouteList{}
if err := r.List(ctx, hrList, client.MatchingFields{
indexer.ExtensionRef: indexer.GenIndexKey(namespace, name),
}); err != nil {
r.Log.Error(err, "failed to list httproutes by extension reference", "extension", name)
return nil
}
requests := make([]reconcile.Request, 0, len(hrList.Items))
for _, hr := range hrList.Items {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: hr.Namespace,
Name: hr.Name,
},
})
}
return requests
}
func (r *HTTPRouteReconciler) listHTTPRoutesForGateway(ctx context.Context, obj client.Object) []reconcile.Request {
gateway, ok := obj.(*gatewayv1.Gateway)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to Gateway")
}
hrList := &gatewayv1.HTTPRouteList{}
if err := r.List(ctx, hrList, client.MatchingFields{
indexer.ParentRefs: indexer.GenIndexKey(gateway.Namespace, gateway.Name),
}); err != nil {
r.Log.Error(err, "failed to list httproutes by gateway", "gateway", gateway.Name)
return nil
}
requests := make([]reconcile.Request, 0, len(hrList.Items))
for _, hr := range hrList.Items {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: hr.Namespace,
Name: hr.Name,
},
})
}
return requests
}
func (r *HTTPRouteReconciler) processHTTPRouteBackendRefs(tctx *provider.TranslateContext) error {
var terr error
for _, backend := range tctx.BackendRefs {
namespace := string(*backend.Namespace)
name := string(backend.Name)
if backend.Kind != nil && *backend.Kind != "Service" {
terr = fmt.Errorf("kind %s is not supported", *backend.Kind)
continue
}
if backend.Port == nil {
terr = fmt.Errorf("port is required")
continue
}
var service corev1.Service
if err := r.Get(context.TODO(), client.ObjectKey{
Namespace: namespace,
Name: name,
}, &service); err != nil {
terr = err
continue
}
portExists := false
for _, port := range service.Spec.Ports {
if port.Port == int32(*backend.Port) {
portExists = true
break
}
}
if !portExists {
terr = fmt.Errorf("port %d not found in service %s", *backend.Port, name)
continue
}
endpointSliceList := new(discoveryv1.EndpointSliceList)
if err := r.List(context.TODO(), endpointSliceList,
client.InNamespace(namespace),
client.MatchingLabels{
discoveryv1.LabelServiceName: name,
},
); err != nil {
r.Log.Error(err, "failed to list endpoint slices", "namespace", namespace, "name", name)
terr = err
continue
}
tctx.EndpointSlices[client.ObjectKey{
Namespace: namespace,
Name: name,
}] = endpointSliceList.Items
}
return terr
}
func (t *HTTPRouteReconciler) processHTTPRoute(tctx *provider.TranslateContext, httpRoute *gatewayv1.HTTPRoute) error {
var terror error
for _, rule := range httpRoute.Spec.Rules {
for _, filter := range rule.Filters {
if filter.Type != gatewayv1.HTTPRouteFilterExtensionRef || filter.ExtensionRef == nil {
continue
}
if filter.ExtensionRef.Kind == "PluginConfig" {
pluginconfig := new(v1alpha1.PluginConfig)
if err := t.Get(context.Background(), client.ObjectKey{
Namespace: httpRoute.GetNamespace(),
Name: string(filter.ExtensionRef.Name),
}, pluginconfig); err != nil {
terror = err
continue
}
tctx.PluginConfigs[types.NamespacedName{
Namespace: httpRoute.GetNamespace(),
Name: string(filter.ExtensionRef.Name),
}] = pluginconfig
}
}
for _, backend := range rule.BackendRefs {
var kind string
if backend.Kind == nil {
kind = "service"
} else {
kind = strings.ToLower(string(*backend.Kind))
}
if kind != "service" {
terror = fmt.Errorf("kind %s is not supported", kind)
continue
}
var ns string
if backend.Namespace == nil {
ns = httpRoute.Namespace
} else {
ns = string(*backend.Namespace)
}
backendNs := gatewayv1.Namespace(ns)
tctx.BackendRefs = append(tctx.BackendRefs, gatewayv1.BackendRef{
BackendObjectReference: gatewayv1.BackendObjectReference{
Name: backend.Name,
Namespace: &backendNs,
Port: backend.Port,
},
})
}
}
return terror
}