-
Notifications
You must be signed in to change notification settings - Fork 840
/
nginx.go
361 lines (309 loc) · 16.3 KB
/
nginx.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
package nginx
import (
"context"
"errors"
"fmt"
"strings"
"github.com/sirupsen/logrus"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
networkingv1 "k8s.io/api/networking/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
"github.com/argoproj/argo-rollouts/utils/defaults"
ingressutil "github.com/argoproj/argo-rollouts/utils/ingress"
logutil "github.com/argoproj/argo-rollouts/utils/log"
"github.com/argoproj/argo-rollouts/utils/record"
)
// Type holds this controller type
const Type = "Nginx"
// ReconcilerConfig describes static configuration data for the nginx reconciler
type ReconcilerConfig struct {
Rollout *v1alpha1.Rollout
Client kubernetes.Interface
Recorder record.EventRecorder
ControllerKind schema.GroupVersionKind
IngressWrapper IngressWrapper
}
type IngressWrapper interface {
Get(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*ingressutil.Ingress, error)
GetCached(namespace, name string) (*ingressutil.Ingress, error)
Patch(ctx context.Context, namespace, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*ingressutil.Ingress, error)
Create(ctx context.Context, namespace string, ingress *ingressutil.Ingress, opts metav1.CreateOptions) (*ingressutil.Ingress, error)
}
// Reconciler holds required fields to reconcile Nginx resources
type Reconciler struct {
cfg ReconcilerConfig
log *logrus.Entry
}
// NewReconciler returns a reconciler struct that brings the canary Ingress into the desired state
func NewReconciler(cfg ReconcilerConfig) *Reconciler {
return &Reconciler{
cfg: cfg,
log: logutil.WithRollout(cfg.Rollout),
}
}
// Type indicates this reconciler is an Nginx reconciler
func (r *Reconciler) Type() string {
return Type
}
func (r *Reconciler) buildCanaryIngress(stableIngress *networkingv1.Ingress, name string, desiredWeight int32) (*ingressutil.Ingress, error) {
stableIngressName := r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.Nginx.StableIngress
stableServiceName := r.cfg.Rollout.Spec.Strategy.Canary.StableService
canaryServiceName := r.cfg.Rollout.Spec.Strategy.Canary.CanaryService
annotationPrefix := defaults.GetCanaryIngressAnnotationPrefixOrDefault(r.cfg.Rollout)
desiredCanaryIngress := &networkingv1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Annotations: map[string]string{},
},
Spec: networkingv1.IngressSpec{
Rules: make([]networkingv1.IngressRule, 0), // We have no way of knowing yet how many rules there will be
},
}
// Preserve TLS from stable ingress
if stableIngress.Spec.TLS != nil {
desiredCanaryIngress.Spec.TLS = make([]networkingv1.IngressTLS, len(stableIngress.Spec.TLS))
for it := 0; it < len(stableIngress.Spec.TLS); it++ {
stableIngress.Spec.TLS[it].DeepCopyInto(&desiredCanaryIngress.Spec.TLS[it])
}
}
// Preserve ingressClassName from stable ingress
if stableIngress.Spec.IngressClassName != nil {
desiredCanaryIngress.Spec.IngressClassName = stableIngress.Spec.IngressClassName
}
// Must preserve ingress.class on canary ingress, no other annotations matter
// See: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#canary
if val, ok := stableIngress.Annotations["kubernetes.io/ingress.class"]; ok {
desiredCanaryIngress.Annotations["kubernetes.io/ingress.class"] = val
}
// Ensure canaryIngress is owned by this Rollout for cleanup
desiredCanaryIngress.SetOwnerReferences([]metav1.OwnerReference{*metav1.NewControllerRef(r.cfg.Rollout, r.cfg.ControllerKind)})
// Copy only the rules which reference the stableService from the stableIngress to the canaryIngress
// and change service backend to canaryService. Rules **not** referencing the stableIngress will be ignored.
for ir := 0; ir < len(stableIngress.Spec.Rules); ir++ {
var hasStableServiceBackendRule bool
ingressRule := stableIngress.Spec.Rules[ir].DeepCopy()
// Update all backends pointing to the stableService to point to the canaryService now
for ip := 0; ip < len(ingressRule.HTTP.Paths); ip++ {
if ingressRule.HTTP.Paths[ip].Backend.Service.Name == stableServiceName {
hasStableServiceBackendRule = true
ingressRule.HTTP.Paths[ip].Backend.Service.Name = canaryServiceName
}
}
// If this rule was using the specified stableService backend, append it to the canary Ingress spec
if hasStableServiceBackendRule {
desiredCanaryIngress.Spec.Rules = append(desiredCanaryIngress.Spec.Rules, *ingressRule)
}
}
if len(desiredCanaryIngress.Spec.Rules) == 0 {
return nil, fmt.Errorf("ingress `%s` has no rules using service %s backend", stableIngressName, stableServiceName)
}
// Process additional annotations, would commonly be things like `canary-by-header` or `load-balance`
for k, v := range r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.Nginx.AdditionalIngressAnnotations {
if !strings.HasPrefix(k, annotationPrefix) {
k = fmt.Sprintf("%s/%s", annotationPrefix, k)
}
desiredCanaryIngress.Annotations[k] = v
}
// Always set `canary` and `canary-weight` - `canary-by-header` and `canary-by-cookie`, if set, will always take precedence
desiredCanaryIngress.Annotations[fmt.Sprintf("%s/canary", annotationPrefix)] = "true"
desiredCanaryIngress.Annotations[fmt.Sprintf("%s/canary-weight", annotationPrefix)] = fmt.Sprintf("%d", desiredWeight)
if r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.MaxTrafficWeight != nil {
weightTotal := *r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.MaxTrafficWeight
desiredCanaryIngress.Annotations[fmt.Sprintf("%s/canary-weight-total", annotationPrefix)] = fmt.Sprintf("%d", weightTotal)
}
return ingressutil.NewIngress(desiredCanaryIngress), nil
}
func (r *Reconciler) buildLegacyCanaryIngress(stableIngress *extensionsv1beta1.Ingress, name string, desiredWeight int32) (*ingressutil.Ingress, error) {
stableIngressName := r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.Nginx.StableIngress
stableServiceName := r.cfg.Rollout.Spec.Strategy.Canary.StableService
canaryServiceName := r.cfg.Rollout.Spec.Strategy.Canary.CanaryService
annotationPrefix := defaults.GetCanaryIngressAnnotationPrefixOrDefault(r.cfg.Rollout)
desiredCanaryIngress := &extensionsv1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Annotations: map[string]string{},
},
Spec: extensionsv1beta1.IngressSpec{
Rules: make([]extensionsv1beta1.IngressRule, 0), // We have no way of knowing yet how many rules there will be
},
}
// Preserve TLS from stable ingress
if stableIngress.Spec.TLS != nil {
desiredCanaryIngress.Spec.TLS = make([]extensionsv1beta1.IngressTLS, len(stableIngress.Spec.TLS))
for it := 0; it < len(stableIngress.Spec.TLS); it++ {
stableIngress.Spec.TLS[it].DeepCopyInto(&desiredCanaryIngress.Spec.TLS[it])
}
}
// Preserve ingressClassName from stable ingress
if stableIngress.Spec.IngressClassName != nil {
desiredCanaryIngress.Spec.IngressClassName = stableIngress.Spec.IngressClassName
}
// Must preserve ingress.class on canary ingress, no other annotations matter
// See: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#canary
if val, ok := stableIngress.Annotations["kubernetes.io/ingress.class"]; ok {
desiredCanaryIngress.Annotations["kubernetes.io/ingress.class"] = val
}
// Ensure canaryIngress is owned by this Rollout for cleanup
desiredCanaryIngress.SetOwnerReferences([]metav1.OwnerReference{*metav1.NewControllerRef(r.cfg.Rollout, r.cfg.ControllerKind)})
// Copy only the rules which reference the stableService from the stableIngress to the canaryIngress
// and change service backend to canaryService. Rules **not** referencing the stableIngress will be ignored.
for ir := 0; ir < len(stableIngress.Spec.Rules); ir++ {
var hasStableServiceBackendRule bool
ingressRule := stableIngress.Spec.Rules[ir].DeepCopy()
// Update all backends pointing to the stableService to point to the canaryService now
for ip := 0; ip < len(ingressRule.HTTP.Paths); ip++ {
if ingressRule.HTTP.Paths[ip].Backend.ServiceName == stableServiceName {
hasStableServiceBackendRule = true
ingressRule.HTTP.Paths[ip].Backend.ServiceName = canaryServiceName
}
}
// If this rule was using the specified stableService backend, append it to the canary Ingress spec
if hasStableServiceBackendRule {
desiredCanaryIngress.Spec.Rules = append(desiredCanaryIngress.Spec.Rules, *ingressRule)
}
}
if len(desiredCanaryIngress.Spec.Rules) == 0 {
return nil, fmt.Errorf("ingress `%s` has no rules using service %s backend", stableIngressName, stableServiceName)
}
// Process additional annotations, would commonly be things like `canary-by-header` or `load-balance`
for k, v := range r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.Nginx.AdditionalIngressAnnotations {
if !strings.HasPrefix(k, annotationPrefix) {
k = fmt.Sprintf("%s/%s", annotationPrefix, k)
}
desiredCanaryIngress.Annotations[k] = v
}
// Always set `canary` and `canary-weight` - `canary-by-header` and `canary-by-cookie`, if set, will always take precedence
desiredCanaryIngress.Annotations[fmt.Sprintf("%s/canary", annotationPrefix)] = "true"
desiredCanaryIngress.Annotations[fmt.Sprintf("%s/canary-weight", annotationPrefix)] = fmt.Sprintf("%d", desiredWeight)
if r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.MaxTrafficWeight != nil {
weightTotal := *r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.MaxTrafficWeight
desiredCanaryIngress.Annotations[fmt.Sprintf("%s/canary-weight-total", annotationPrefix)] = fmt.Sprintf("%d", weightTotal)
}
return ingressutil.NewLegacyIngress(desiredCanaryIngress), nil
}
// canaryIngress returns the desired state of the canary ingress
func (r *Reconciler) canaryIngress(stableIngress *ingressutil.Ingress, name string, desiredWeight int32) (*ingressutil.Ingress, error) {
switch stableIngress.Mode() {
case ingressutil.IngressModeNetworking:
networkingIngress, err := stableIngress.GetNetworkingIngress()
if err != nil {
return nil, err
}
return r.buildCanaryIngress(networkingIngress, name, desiredWeight)
case ingressutil.IngressModeExtensions:
extensionsIngress, err := stableIngress.GetExtensionsIngress()
if err != nil {
return nil, err
}
return r.buildLegacyCanaryIngress(extensionsIngress, name, desiredWeight)
default:
return nil, errors.New("undefined ingress mode")
}
}
// SetWeight modifies Nginx Ingress resources to reach desired state
func (r *Reconciler) SetWeight(desiredWeight int32, additionalDestinations ...v1alpha1.WeightDestination) error {
if ingresses := r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.Nginx.StableIngresses; ingresses != nil {
return r.SetWeightPerIngress(desiredWeight, ingresses)
} else {
return r.SetWeightPerIngress(desiredWeight, []string{r.cfg.Rollout.Spec.Strategy.Canary.TrafficRouting.Nginx.StableIngress})
}
}
// SetWeightMultiIngress modifies each Nginx Ingress resource to reach desired state in the scenario of a rollout
// having multiple Ngnix Ingress resources.
func (r *Reconciler) SetWeightPerIngress(desiredWeight int32, ingresses []string) error {
for _, ingress := range ingresses {
ctx := context.TODO()
stableIngressName := ingress
canaryIngressName := ingressutil.GetCanaryIngressName(r.cfg.Rollout.GetName(), stableIngressName)
// Check if stable ingress exists (from lister, which has a cache), error if it does not
stableIngress, err := r.cfg.IngressWrapper.GetCached(r.cfg.Rollout.Namespace, stableIngressName)
if err != nil {
r.log.WithField(logutil.IngressKey, stableIngressName).WithField("err", err.Error()).Error("error retrieving stableIngress")
return fmt.Errorf("error retrieving stableIngress `%s` from cache: %v", stableIngressName, err)
}
// Check if canary ingress exists (from lister which has a cache), determines whether we later call Create() or Update()
canaryIngress, err := r.cfg.IngressWrapper.GetCached(r.cfg.Rollout.Namespace, canaryIngressName)
canaryIngressExists := true
if err != nil {
if !k8serrors.IsNotFound(err) {
// An error other than "not found" occurred
r.log.WithField(logutil.IngressKey, canaryIngressName).WithField("err", err.Error()).Error("error retrieving canary ingress")
return fmt.Errorf("error retrieving canary ingress `%s` from cache: %v", canaryIngressName, err)
}
r.log.WithField(logutil.IngressKey, canaryIngressName).Infof("canary ingress not found")
canaryIngressExists = false
}
// Construct the desired canary Ingress resource
desiredCanaryIngress, err := r.canaryIngress(stableIngress, canaryIngressName, desiredWeight)
if err != nil {
r.log.WithField(logutil.IngressKey, canaryIngressName).Error(err.Error())
return err
}
if !canaryIngressExists {
r.cfg.Recorder.Eventf(r.cfg.Rollout, record.EventOptions{EventReason: "CreatingCanaryIngress"}, "Creating canary ingress `%s` with weight `%d`", canaryIngressName, desiredWeight)
_, err = r.cfg.IngressWrapper.Create(ctx, r.cfg.Rollout.Namespace, desiredCanaryIngress, metav1.CreateOptions{})
if err == nil {
continue
}
if !k8serrors.IsAlreadyExists(err) {
r.log.WithField(logutil.IngressKey, canaryIngressName).WithField("err", err.Error()).Error("error creating canary ingress")
return fmt.Errorf("error creating canary ingress `%s`: %v", canaryIngressName, err)
}
// Canary ingress was created by a different reconcile call before this one could complete (race)
// This means we just read it from the API now (instead of cache) and continue with the normal
// flow we take when the canary already existed.
canaryIngress, err = r.cfg.IngressWrapper.Get(ctx, r.cfg.Rollout.Namespace, canaryIngressName, metav1.GetOptions{})
if err != nil {
r.log.WithField(logutil.IngressKey, canaryIngressName).Error(err.Error())
return fmt.Errorf("error retrieving canary ingress `%s` from api: %v", canaryIngressName, err)
}
}
// Canary Ingress already exists, apply a patch if needed
// Only modify canaryIngress if it is controlled by this Rollout
if !metav1.IsControlledBy(canaryIngress.GetObjectMeta(), r.cfg.Rollout) {
r.log.WithField(logutil.IngressKey, canaryIngressName).Error("canary ingress controlled by different object")
return fmt.Errorf("canary ingress `%s` controlled by different object", canaryIngressName)
}
// Make patches
patch, modified, err := ingressutil.BuildIngressPatch(canaryIngress.Mode(), canaryIngress,
desiredCanaryIngress, ingressutil.WithAnnotations(), ingressutil.WithLabels(), ingressutil.WithSpec())
if err != nil {
r.log.WithField(logutil.IngressKey, canaryIngressName).WithField("err", err.Error()).Error("error constructing canary ingress patch")
return fmt.Errorf("error constructing canary ingress patch for `%s`: %v", canaryIngressName, err)
}
if !modified {
r.log.WithField(logutil.IngressKey, canaryIngressName).Info("No changes to canary ingress - skipping patch")
continue
}
r.log.WithField(logutil.IngressKey, canaryIngressName).WithField("patch", string(patch)).Debug("applying canary Ingress patch")
r.log.WithField(logutil.IngressKey, canaryIngressName).WithField("desiredWeight", desiredWeight).Info("updating canary Ingress")
r.cfg.Recorder.Eventf(r.cfg.Rollout, record.EventOptions{EventReason: "PatchingCanaryIngress"}, "Updating Ingress `%s` to desiredWeight '%d'", canaryIngressName, desiredWeight)
_, err = r.cfg.IngressWrapper.Patch(ctx, r.cfg.Rollout.Namespace, canaryIngressName, types.MergePatchType, patch, metav1.PatchOptions{})
if err != nil {
r.log.WithField(logutil.IngressKey, canaryIngressName).WithField("err", err.Error()).Error("error patching canary ingress")
return fmt.Errorf("error patching canary ingress `%s`: %v", canaryIngressName, err)
}
}
return nil
}
func (r *Reconciler) SetHeaderRoute(headerRouting *v1alpha1.SetHeaderRoute) error {
return nil
}
func (r *Reconciler) VerifyWeight(desiredWeight int32, additionalDestinations ...v1alpha1.WeightDestination) (*bool, error) {
return nil, nil
}
// UpdateHash informs a traffic routing reconciler about new canary/stable pod hashes
func (r *Reconciler) UpdateHash(canaryHash, stableHash string, additionalDestinations ...v1alpha1.WeightDestination) error {
return nil
}
func (r *Reconciler) SetMirrorRoute(setMirrorRoute *v1alpha1.SetMirrorRoute) error {
return nil
}
func (r *Reconciler) RemoveManagedRoutes() error {
return nil
}