forked from projectcontour/contour
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatewayclass.go
327 lines (281 loc) · 11 KB
/
gatewayclass.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
// Copyright Project Contour Authors
// 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 controller
import (
"context"
"fmt"
"strings"
"github.com/projectcontour/contour/apis/projectcontour/v1alpha1"
contour_api_v1alpha1 "github.com/projectcontour/contour/apis/projectcontour/v1alpha1"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
gatewayapi_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1"
)
// gatewayClassReconciler reconciles GatewayClass objects.
type gatewayClassReconciler struct {
gatewayController gatewayapi_v1beta1.GatewayController
client client.Client
log logr.Logger
}
func NewGatewayClassController(mgr manager.Manager, gatewayController string) (controller.Controller, error) {
r := &gatewayClassReconciler{
gatewayController: gatewayapi_v1beta1.GatewayController(gatewayController),
client: mgr.GetClient(),
log: ctrl.Log.WithName("gatewayclass-controller"),
}
c, err := controller.New("gatewayclass-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return nil, err
}
if err := c.Watch(
&source.Kind{Type: &gatewayapi_v1beta1.GatewayClass{}},
&handler.EnqueueRequestForObject{},
predicate.NewPredicateFuncs(r.hasMatchingController),
); err != nil {
return nil, err
}
// Watch ContourDeployments since they can be used as parameters for
// GatewayClasses.
if err := c.Watch(
&source.Kind{Type: &contour_api_v1alpha1.ContourDeployment{}},
handler.EnqueueRequestsFromMapFunc(r.mapContourDeploymentToGatewayClasses),
); err != nil {
return nil, err
}
return c, nil
}
func (r *gatewayClassReconciler) hasMatchingController(obj client.Object) bool {
gatewayClass, ok := obj.(*gatewayapi_v1beta1.GatewayClass)
if !ok {
return false
}
return gatewayClass.Spec.ControllerName == r.gatewayController
}
// mapContourDeploymentToGatewayClasses returns a list of reconcile requests
// for all provisioner-controlled GatewayClasses that have a ParametersRef to
// the specified ContourDeployment object.
func (r *gatewayClassReconciler) mapContourDeploymentToGatewayClasses(contourDeployment client.Object) []reconcile.Request {
var gatewayClasses gatewayapi_v1beta1.GatewayClassList
if err := r.client.List(context.Background(), &gatewayClasses); err != nil {
r.log.Error(err, "error listing gateway classes")
return nil
}
var reconciles []reconcile.Request
for i := range gatewayClasses.Items {
gc := &gatewayClasses.Items[i]
if !r.hasMatchingController(gc) {
continue
}
if !isContourDeploymentRef(gc.Spec.ParametersRef) {
continue
}
if gc.Spec.ParametersRef.Namespace == nil || string(*gc.Spec.ParametersRef.Namespace) != contourDeployment.GetNamespace() {
continue
}
if gc.Spec.ParametersRef.Name != contourDeployment.GetName() {
continue
}
reconciles = append(reconciles, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: gc.Name,
},
})
}
return reconciles
}
func (r *gatewayClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
gatewayClass := &gatewayapi_v1beta1.GatewayClass{}
if err := r.client.Get(ctx, req.NamespacedName, gatewayClass); err != nil {
// GatewayClass no longer exists, nothing to do.
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}
// Error reading the object, so requeue the request.
return ctrl.Result{}, fmt.Errorf("failed to get gatewayclass %s: %w", req, err)
}
// Theoretically all event sources should be filtered already, but doesn't hurt
// to double-check this here to ensure we only reconcile gateway classes the
// provisioner controls.
if !r.hasMatchingController(gatewayClass) {
return ctrl.Result{}, nil
}
ok, params, err := r.isValidParametersRef(ctx, gatewayClass.Spec.ParametersRef)
if err != nil {
return ctrl.Result{}, fmt.Errorf("error checking gateway class's parametersRef: %w", err)
}
if !ok {
if err := r.setAcceptedCondition(
ctx,
gatewayClass,
metav1.ConditionFalse,
gatewayapi_v1beta1.GatewayClassReasonInvalidParameters,
"Invalid ParametersRef, must be a reference to an existing namespaced projectcontour.io/ContourDeployment resource",
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to set gateway class %s Accepted condition: %w", req, err)
}
return ctrl.Result{}, nil
}
// If parameters are referenced, validate the values.
if params != nil {
var invalidParamsMessages []string
if params.Spec.Envoy != nil {
switch params.Spec.Envoy.WorkloadType {
// valid values, nothing to do
case "", contour_api_v1alpha1.WorkloadTypeDaemonSet, contour_api_v1alpha1.WorkloadTypeDeployment:
// invalid value, set message
default:
msg := fmt.Sprintf("invalid ContourDeployment spec.envoy.workloadType %q, must be DaemonSet or Deployment", params.Spec.Envoy.WorkloadType)
invalidParamsMessages = append(invalidParamsMessages, msg)
}
if params.Spec.Envoy.NetworkPublishing != nil {
switch params.Spec.Envoy.NetworkPublishing.Type {
// valid values, nothing to do
case "", contour_api_v1alpha1.LoadBalancerServicePublishingType, contour_api_v1alpha1.NodePortServicePublishingType, contour_api_v1alpha1.ClusterIPServicePublishingType:
// invalid value, set message
default:
msg := fmt.Sprintf("invalid ContourDeployment spec.envoy.networkPublishing.type %q, must be LoadBalancerService, NoderPortService or ClusterIPService",
params.Spec.Envoy.NetworkPublishing.Type)
invalidParamsMessages = append(invalidParamsMessages, msg)
}
switch params.Spec.Envoy.NetworkPublishing.ExternalTrafficPolicy {
case "", corev1.ServiceExternalTrafficPolicyTypeCluster, corev1.ServiceExternalTrafficPolicyTypeLocal:
default:
msg := fmt.Sprintf("invalid ContourDeployment spec.envoy.networkPublishing.externalTrafficPolicy %q, must be Local or Cluster",
params.Spec.Envoy.NetworkPublishing.ExternalTrafficPolicy)
invalidParamsMessages = append(invalidParamsMessages, msg)
}
}
if params.Spec.Envoy.ExtraVolumeMounts != nil {
volumes := map[string]struct{}{}
for _, vol := range params.Spec.Envoy.ExtraVolumes {
volumes[vol.Name] = struct{}{}
}
for _, mnt := range params.Spec.Envoy.ExtraVolumeMounts {
if _, ok := volumes[mnt.Name]; !ok {
msg := fmt.Sprintf("invalid ContourDeployment spec.envoy.extraVolumeMounts, mount to unknown volume: %q", mnt.Name)
invalidParamsMessages = append(invalidParamsMessages, msg)
}
}
}
switch params.Spec.Envoy.LogLevel {
// valid values, nothing to do.
case "", v1alpha1.TraceLog, v1alpha1.DebugLog, v1alpha1.InfoLog, v1alpha1.WarnLog, v1alpha1.ErrorLog, v1alpha1.CriticalLog, v1alpha1.OffLog:
// invalid value, set message.
default:
msg := fmt.Sprintf("invalid ContourDeployment spec.envoy.logLevel %q, must be trace, debug, info, warn, error, critical or off",
params.Spec.Envoy.LogLevel)
invalidParamsMessages = append(invalidParamsMessages, msg)
}
}
if len(invalidParamsMessages) > 0 {
if err := r.setAcceptedCondition(
ctx,
gatewayClass,
metav1.ConditionFalse,
gatewayapi_v1beta1.GatewayClassReasonInvalidParameters,
strings.Join(invalidParamsMessages, "; "),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to set gateway class %s Accepted condition: %w", req, err)
}
return ctrl.Result{}, nil
}
}
if err := r.setAcceptedCondition(ctx, gatewayClass, metav1.ConditionTrue, gatewayapi_v1beta1.GatewayClassReasonAccepted, "GatewayClass has been accepted by the controller"); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to set gateway class %s Accepted condition: %w", req, err)
}
return ctrl.Result{}, nil
}
func (r *gatewayClassReconciler) setAcceptedCondition(
ctx context.Context,
gatewayClass *gatewayapi_v1beta1.GatewayClass,
status metav1.ConditionStatus,
reason gatewayapi_v1beta1.GatewayClassConditionReason,
message string,
) error {
currentAcceptedCondition := metav1.Condition{
Type: string(gatewayapi_v1beta1.GatewayClassConditionStatusAccepted),
Status: status,
ObservedGeneration: gatewayClass.Generation,
LastTransitionTime: metav1.Now(),
Reason: string(reason),
Message: message,
}
var newConds []metav1.Condition
for _, cond := range gatewayClass.Status.Conditions {
if cond.Type == string(gatewayapi_v1beta1.GatewayClassConditionStatusAccepted) {
if cond.Status == status {
// If status hasn't changed, don't change the condition, just
// update the generation.
currentAcceptedCondition = cond
currentAcceptedCondition.ObservedGeneration = gatewayClass.Generation
}
continue
}
newConds = append(newConds, cond)
}
r.log.WithValues("gatewayclass-name", gatewayClass.Name).Info(fmt.Sprintf("setting gateway class's Accepted condition to %s", status))
// nolint:gocritic
gatewayClass.Status.Conditions = append(newConds, currentAcceptedCondition)
if err := r.client.Status().Update(ctx, gatewayClass); err != nil {
return fmt.Errorf("failed to set gatewayclass %s accepted condition: %w", gatewayClass.Name, err)
}
return nil
}
// isValidParametersRef returns true if the provided ParametersReference is
// to a ContourDeployment resource that exists.
func (r *gatewayClassReconciler) isValidParametersRef(ctx context.Context, ref *gatewayapi_v1beta1.ParametersReference) (bool, *contour_api_v1alpha1.ContourDeployment, error) {
if ref == nil {
return true, nil, nil
}
if !isContourDeploymentRef(ref) {
return false, nil, nil
}
key := client.ObjectKey{
Namespace: string(*ref.Namespace),
Name: ref.Name,
}
params := &contour_api_v1alpha1.ContourDeployment{}
if err := r.client.Get(ctx, key, params); err != nil {
if errors.IsNotFound(err) {
return false, nil, nil
}
return false, nil, err
}
return true, params, nil
}
func isContourDeploymentRef(ref *gatewayapi_v1beta1.ParametersReference) bool {
if ref == nil {
return false
}
if string(ref.Group) != contour_api_v1alpha1.GroupVersion.Group {
return false
}
if string(ref.Kind) != "ContourDeployment" {
return false
}
if ref.Namespace == nil {
return false
}
return true
}