-
Notifications
You must be signed in to change notification settings - Fork 27
/
rate_limiting_wasmplugin_controller.go
403 lines (337 loc) · 14.3 KB
/
rate_limiting_wasmplugin_controller.go
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
Copyright 2021 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"encoding/json"
"fmt"
"sort"
"github.com/go-logr/logr"
istioextensionsv1alpha1 "istio.io/api/extensions/v1alpha1"
istioclientgoextensionv1alpha1 "istio.io/client-go/pkg/apis/extensions/v1alpha1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1"
kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2"
"github.com/kuadrant/kuadrant-operator/pkg/common"
kuadrantistioutils "github.com/kuadrant/kuadrant-operator/pkg/istio"
kuadrantgatewayapi "github.com/kuadrant/kuadrant-operator/pkg/library/gatewayapi"
"github.com/kuadrant/kuadrant-operator/pkg/library/mappers"
"github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers"
"github.com/kuadrant/kuadrant-operator/pkg/library/utils"
"github.com/kuadrant/kuadrant-operator/pkg/rlptools"
"github.com/kuadrant/kuadrant-operator/pkg/rlptools/wasm"
)
const (
HTTPRouteGatewayParentField = ".metadata.parentRefs.gateway"
)
// RateLimitingWASMPluginReconciler reconciles a WASMPlugin object for rate limiting
type RateLimitingWASMPluginReconciler struct {
*reconcilers.BaseReconciler
}
//+kubebuilder:rbac:groups=extensions.istio.io,resources=wasmplugins,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gateways,verbs=get;list;watch;update;patch
//+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=httproutes,verbs=get;list;watch;update;patch
//+kubebuilder:rbac:groups=kuadrant.io,resources=ratelimitpolicies,verbs=get;list;watch;update;patch
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *RateLimitingWASMPluginReconciler) Reconcile(eventCtx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := r.Logger().WithValues("Gateway", req.NamespacedName)
logger.Info("Reconciling rate limiting WASMPlugin")
ctx := logr.NewContext(eventCtx, logger)
gw := &gatewayapiv1.Gateway{}
if err := r.Client().Get(ctx, req.NamespacedName, gw); err != nil {
if apierrors.IsNotFound(err) {
logger.Info("no gateway found")
return ctrl.Result{}, nil
}
logger.Error(err, "failed to get gateway")
return ctrl.Result{}, err
}
if logger.V(1).Enabled() {
jsonData, err := json.MarshalIndent(gw, "", " ")
if err != nil {
return ctrl.Result{}, err
}
logger.V(1).Info(string(jsonData))
}
desired, err := r.desiredRateLimitingWASMPlugin(ctx, gw)
if err != nil {
return ctrl.Result{}, err
}
err = r.ReconcileResource(ctx, &istioclientgoextensionv1alpha1.WasmPlugin{}, desired, rlptools.WASMPluginMutator)
if err != nil {
return ctrl.Result{}, err
}
logger.Info("Rate limiting WASMPlugin reconciled successfully")
return ctrl.Result{}, nil
}
func (r *RateLimitingWASMPluginReconciler) desiredRateLimitingWASMPlugin(ctx context.Context, gw *gatewayapiv1.Gateway) (*istioclientgoextensionv1alpha1.WasmPlugin, error) {
baseLogger, err := logr.FromContext(ctx)
if err != nil {
return nil, err
}
wasmPlugin := &istioclientgoextensionv1alpha1.WasmPlugin{
TypeMeta: metav1.TypeMeta{
Kind: "WasmPlugin",
APIVersion: "extensions.istio.io/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: rlptools.WASMPluginName(gw),
Namespace: gw.Namespace,
},
Spec: istioextensionsv1alpha1.WasmPlugin{
Selector: kuadrantistioutils.WorkloadSelectorFromGateway(ctx, r.Client(), gw),
Url: rlptools.WASMFilterImageURL,
PluginConfig: nil,
// Insert plugin before Istio stats filters and after Istio authorization filters.
Phase: istioextensionsv1alpha1.PluginPhase_STATS,
},
}
logger := baseLogger.WithValues("wasmplugin", client.ObjectKeyFromObject(wasmPlugin))
pluginConfig, err := r.wasmPluginConfig(ctx, gw)
if err != nil {
return nil, err
}
if pluginConfig == nil || len(pluginConfig.RateLimitPolicies) == 0 {
logger.V(1).Info("pluginConfig is empty. Wasmplugin will be deleted if it exists")
utils.TagObjectToDelete(wasmPlugin)
return wasmPlugin, nil
}
pluginConfigStruct, err := pluginConfig.ToStruct()
if err != nil {
return nil, err
}
wasmPlugin.Spec.PluginConfig = pluginConfigStruct
// controller reference
if err := r.SetOwnerReference(gw, wasmPlugin); err != nil {
return nil, err
}
return wasmPlugin, nil
}
func (r *RateLimitingWASMPluginReconciler) wasmPluginConfig(ctx context.Context, gw *gatewayapiv1.Gateway) (*wasm.Plugin, error) {
logger, err := logr.FromContext(ctx)
if err != nil {
return nil, err
}
wasmPlugin := &wasm.Plugin{
FailureMode: wasm.FailureModeDeny,
RateLimitPolicies: make([]wasm.RateLimitPolicy, 0),
}
t, err := r.topologyIndexesFromGateway(ctx, gw)
if err != nil {
return nil, err
}
rateLimitPolicies := t.PoliciesFromGateway(gw)
logger.V(1).Info("wasmPluginConfig", "#RLPS", len(rateLimitPolicies))
// Sort RLPs for consistent comparison with existing objects
sort.Sort(kuadrantgatewayapi.PolicyByTargetRefKindAndCreationTimeStamp(rateLimitPolicies))
for _, policy := range rateLimitPolicies {
rlp := policy.(*kuadrantv1beta2.RateLimitPolicy)
wasmRLP, err := r.wasmRateLimitPolicy(ctx, t, rlp, gw, rateLimitPolicies)
if err != nil {
return nil, err
}
if wasmRLP == nil {
// skip this RLP
continue
}
wasmPlugin.RateLimitPolicies = append(wasmPlugin.RateLimitPolicies, *wasmRLP)
}
return wasmPlugin, nil
}
func (r *RateLimitingWASMPluginReconciler) topologyIndexesFromGateway(ctx context.Context, gw *gatewayapiv1.Gateway) (*kuadrantgatewayapi.TopologyIndexes, error) {
logger, err := logr.FromContext(ctx)
if err != nil {
return nil, err
}
routeList := &gatewayapiv1.HTTPRouteList{}
// Get all the routes having the gateway as parent
err = r.Client().List(ctx, routeList, client.MatchingFields{HTTPRouteGatewayParentField: client.ObjectKeyFromObject(gw).String()})
logger.V(1).Info("topologyIndexesFromGateway: list httproutes from gateway",
"gateway", client.ObjectKeyFromObject(gw),
"#HTTPRoutes", len(routeList.Items),
"err", err)
if err != nil {
return nil, err
}
rlpList := &kuadrantv1beta2.RateLimitPolicyList{}
// Get all the rate limit policies
err = r.Client().List(ctx, rlpList)
logger.V(1).Info("topologyIndexesFromGateway: list rate limit policies",
"#RLPS", len(rlpList.Items),
"err", err)
if err != nil {
return nil, err
}
policies := utils.Map(rlpList.Items, func(p kuadrantv1beta2.RateLimitPolicy) kuadrantgatewayapi.Policy { return &p })
t, err := kuadrantgatewayapi.NewTopology(
kuadrantgatewayapi.WithGateways([]*gatewayapiv1.Gateway{gw}),
kuadrantgatewayapi.WithRoutes(utils.Map(routeList.Items, ptr.To[gatewayapiv1.HTTPRoute])),
kuadrantgatewayapi.WithPolicies(policies),
kuadrantgatewayapi.WithLogger(logger),
)
if err != nil {
return nil, err
}
return kuadrantgatewayapi.NewTopologyIndexes(t), nil
}
func (r *RateLimitingWASMPluginReconciler) wasmRateLimitPolicy(ctx context.Context, t *kuadrantgatewayapi.TopologyIndexes, rlp *kuadrantv1beta2.RateLimitPolicy, gw *gatewayapiv1.Gateway, affectedPolices []kuadrantgatewayapi.Policy) (*wasm.RateLimitPolicy, error) {
logger, _ := logr.FromContext(ctx)
route, err := r.routeFromRLP(ctx, t, rlp, gw)
if err != nil {
return nil, err
}
if route == nil {
// no need to add the policy if there are no routes;
// a rlp can return no rules if all its limits fail to match any route rule
// or targeting a gateway with no "free" routes. "free" meaning no route with policies targeting it
return nil, nil
}
// narrow the list of hostnames specified in the route so we don't generate wasm rules that only apply to other gateways
// this is a no-op for the gateway rlp
gwHostnames := kuadrantgatewayapi.GatewayHostnames(gw)
if len(gwHostnames) == 0 {
gwHostnames = []gatewayapiv1.Hostname{"*"}
}
hostnames := kuadrantgatewayapi.FilterValidSubdomains(gwHostnames, route.Spec.Hostnames)
if len(hostnames) == 0 { // it should only happen when the route specifies no hostnames
hostnames = gwHostnames
}
//
// The route selectors logic rely on the "hostnames" field of the route object.
// However, routes effective hostname can be inherited from parent gateway,
// hence it depends on the context as multiple gateways can be targeted by a route
// The route selectors logic needs to be refactored
// or just deleted as soon as the HTTPRoute has name in the route object
//
routeWithEffectiveHostnames := route.DeepCopy()
routeWithEffectiveHostnames.Spec.Hostnames = hostnames
// Policy limits may be overridden by a gateway policy for route policies
if kuadrantgatewayapi.IsTargetRefHTTPRoute(rlp.GetTargetRef()) {
filteredPolicies := utils.Filter(affectedPolices, func(p kuadrantgatewayapi.Policy) bool {
return kuadrantgatewayapi.IsTargetRefGateway(p.GetTargetRef()) && p.GetUID() != rlp.GetUID()
})
for _, policy := range filteredPolicies {
p := policy.(*kuadrantv1beta2.RateLimitPolicy)
if p.Spec.Overrides != nil {
rlp.Spec.CommonSpec().Limits = p.Spec.Overrides.Limits
logger.V(1).Info("applying overrides from parent policy", "parentPolicy", client.ObjectKeyFromObject(p))
break
}
}
}
rules := rlptools.WasmRules(rlp, routeWithEffectiveHostnames)
if len(rules) == 0 {
// no need to add the policy if there are no rules; a rlp can return no rules if all its limits fail to match any route rule
return nil, nil
}
return &wasm.RateLimitPolicy{
Name: client.ObjectKeyFromObject(rlp).String(),
Domain: rlptools.LimitsNamespaceFromRLP(rlp),
Hostnames: utils.HostnamesToStrings(hostnames), // we might be listing more hostnames than needed due to route selectors hostnames possibly being more restrictive
Service: common.KuadrantRateLimitClusterName,
Rules: rules,
}, nil
}
func (r *RateLimitingWASMPluginReconciler) routeFromRLP(ctx context.Context, t *kuadrantgatewayapi.TopologyIndexes, rlp *kuadrantv1beta2.RateLimitPolicy, gw *gatewayapiv1.Gateway) (*gatewayapiv1.HTTPRoute, error) {
logger, err := logr.FromContext(ctx)
if err != nil {
return nil, err
}
route := t.GetPolicyHTTPRoute(rlp)
if route == nil {
// The policy is targeting a gateway
// This gateway policy will be enforced into all HTTPRoutes that do not have a policy attached to it
// Build imaginary route with all the routes not having a RLP targeting it
untargetedRoutes := t.GetUntargetedRoutes(gw)
if len(untargetedRoutes) == 0 {
// For policies targeting a gateway, when no httproutes is attached to the gateway, skip wasm config
// test wasm config when no http routes attached to the gateway
logger.V(1).Info("no untargeted httproutes attached to the targeted gateway, skipping wasm config for the gateway rlp", "ratelimitpolicy", client.ObjectKeyFromObject(rlp))
return nil, nil
}
untargetedRules := make([]gatewayapiv1.HTTPRouteRule, 0)
for idx := range untargetedRoutes {
untargetedRules = append(untargetedRules, untargetedRoutes[idx].Spec.Rules...)
}
gwHostnamesTmp := kuadrantgatewayapi.TargetHostnames(gw)
gwHostnames := utils.Map(gwHostnamesTmp, func(str string) gatewayapiv1.Hostname { return gatewayapiv1.Hostname(str) })
route = &gatewayapiv1.HTTPRoute{
Spec: gatewayapiv1.HTTPRouteSpec{
Hostnames: gwHostnames,
Rules: untargetedRules,
},
}
}
return route, nil
}
// addHTTPRouteByGatewayIndexer declares an index key that we can later use with the client as a pseudo-field name,
// allowing to query all the routes parented by a given gateway
// to prevent creating the same index field multiple times, the function is declared private to be
// called only by this controller
func addHTTPRouteByGatewayIndexer(mgr ctrl.Manager, baseLogger logr.Logger) error {
if err := mgr.GetFieldIndexer().IndexField(context.Background(), &gatewayapiv1.HTTPRoute{}, HTTPRouteGatewayParentField, func(rawObj client.Object) []string {
// grab the route object, extract the parents
route, assertionOk := rawObj.(*gatewayapiv1.HTTPRoute)
if !assertionOk {
baseLogger.V(1).Error(fmt.Errorf("%T is not a *gatewayapiv1.HTTPRoute", rawObj), "cannot map")
return nil
}
logger := baseLogger.WithValues("route", client.ObjectKeyFromObject(route).String())
return utils.Map(kuadrantgatewayapi.GetRouteAcceptedGatewayParentKeys(route), func(key client.ObjectKey) string {
logger.V(1).Info("new gateway added", "key", key.String())
return key.String()
})
}); err != nil {
return err
}
return nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *RateLimitingWASMPluginReconciler) SetupWithManager(mgr ctrl.Manager) error {
// Add custom indexer
err := addHTTPRouteByGatewayIndexer(mgr, r.Logger().WithName("routeByGatewayIndexer"))
if err != nil {
return err
}
httpRouteToParentGatewaysEventMapper := mappers.NewHTTPRouteToParentGatewaysEventMapper(
mappers.WithLogger(r.Logger().WithName("httpRouteToParentGatewaysEventMapper")),
)
rlpToParentGatewaysEventMapper := mappers.NewPolicyToParentGatewaysEventMapper(
mappers.WithLogger(r.Logger().WithName("ratelimitpolicyToParentGatewaysEventMapper")),
mappers.WithClient(r.Client()),
)
return ctrl.NewControllerManagedBy(mgr).
// Rate limiting WASMPlugin controller only cares about
// Gateway API Gateway
// Gateway API HTTPRoutes
// Kuadrant RateLimitPolicies
// The type of object being *reconciled* is the Gateway.
// TODO(eguzki): consider having the WasmPlugin as the type of object being *reconciled*
For(&gatewayapiv1.Gateway{}).
Owns(&istioclientgoextensionv1alpha1.WasmPlugin{}).
Watches(
&gatewayapiv1.HTTPRoute{},
handler.EnqueueRequestsFromMapFunc(httpRouteToParentGatewaysEventMapper.Map),
).
Watches(
&kuadrantv1beta2.RateLimitPolicy{},
handler.EnqueueRequestsFromMapFunc(rlpToParentGatewaysEventMapper.Map),
).
Complete(r)
}