-
Notifications
You must be signed in to change notification settings - Fork 28
/
ingress.go
581 lines (507 loc) · 16.7 KB
/
ingress.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package controller
import (
"context"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"time"
zv1 "github.com/zalando-incubator/stackset-controller/pkg/apis/zalando/v1"
clientset "github.com/zalando-incubator/stackset-controller/pkg/client/clientset/versioned"
"github.com/google/go-cmp/cmp"
log "github.com/sirupsen/logrus"
v1beta1 "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
)
const (
stackTrafficWeightsAnnotationKey = "zalando.org/stack-traffic-weights"
backendWeightsAnnotationKey = "zalando.org/backend-weights"
ingressPortName = "ingress"
)
// IngressController is a controller that can manage ingresses for an
// stackset.
type IngressController struct {
logger *log.Entry
kube kubernetes.Interface
appClient clientset.Interface
stackset zv1.StackSet
done chan<- struct{}
interval time.Duration
}
// NewIngressController initializes a new IngressController.
func NewIngressController(client kubernetes.Interface, appClient clientset.Interface, stackset zv1.StackSet, done chan<- struct{}, interval time.Duration) *IngressController {
return &IngressController{
logger: log.WithFields(
log.Fields{
"controller": "ingress",
"stackset": stackset.Name,
"namespace": stackset.Namespace,
},
),
kube: client,
appClient: appClient,
stackset: stackset,
done: done,
interval: interval,
}
}
// Run runs the main loop of the IngressController.
func (c *IngressController) Run(ctx context.Context) {
for {
err := c.runOnce()
if err != nil {
c.logger.Error(err)
}
select {
case <-time.After(c.interval):
case <-ctx.Done():
c.logger.Info("Terminating Ingress Controller.")
c.done <- struct{}{}
return
}
}
}
func (c *IngressController) runOnce() error {
ing, err := getIngress(c.kube, &c.stackset)
if err != nil {
if !errors.IsNotFound(err) {
return err
}
}
heritageLabels := map[string]string{
stacksetHeritageLabelKey: c.stackset.Name,
}
opts := metav1.ListOptions{
LabelSelector: labels.Set(heritageLabels).String(),
}
stacks, err := c.appClient.ZalandoV1().Stacks(c.stackset.Namespace).List(opts)
if err != nil {
return fmt.Errorf("failed to list StackSet stacks of StackSet %s/%s: %v", c.stackset.Namespace, c.stackset.Name, err)
}
// cleanup Ingress if ingress is disabled.
if c.stackset.Spec.Ingress == nil {
if ing != nil {
c.logger.Infof(
"Deleting obsolete Ingress %s/%s for StackSet %s/%s",
ing.Namespace,
ing.Name,
c.stackset.Namespace,
c.stackset.Name,
)
err := c.kube.ExtensionsV1beta1().Ingresses(ing.Namespace).Delete(ing.Name, nil)
if err != nil {
return fmt.Errorf(
"failed to delete Ingress %s/%s for StackSet %s/%s: %v",
ing.Namespace,
ing.Name,
c.stackset.Namespace,
c.stackset.Name,
err,
)
}
// cleanup any per stack ingresses.
for _, stack := range stacks.Items {
err := c.gcStackIngress(stack)
if err != nil {
log.Error(err)
continue
}
}
}
return nil
}
stackStatuses, err := c.getStackStatuses(stacks.Items)
if err != nil {
return fmt.Errorf("failed to get Stack statuses for StackSet %s/%s: %v", c.stackset.Namespace, c.stackset.Name, err)
}
ingress, err := ingressForStackSet(&c.stackset, ing, stackStatuses)
if err != nil {
return fmt.Errorf("failed to generate Ingress for StackSet %s/%s: %v", c.stackset.Namespace, c.stackset.Name, err)
}
if ing == nil {
c.logger.Infof("Creating Ingress %s/%s with %d service backend(s).", ingress.Namespace, ingress.Name, len(stacks.Items))
_, err := c.kube.ExtensionsV1beta1().Ingresses(ingress.Namespace).Create(ingress)
if err != nil {
return err
}
} else {
ing.Status = v1beta1.IngressStatus{}
if !reflect.DeepEqual(ing, ingress) {
c.logger.Debugf("Ingress %s/%s changed: %s", ingress.Namespace, ingress.Name, cmp.Diff(ing, ingress))
c.logger.Infof("Updating Ingress %s/%s with %d service backend(s).", ingress.Namespace, ingress.Name, len(stacks.Items))
_, err := c.kube.ExtensionsV1beta1().Ingresses(ingress.Namespace).Update(ingress)
if err != nil {
return err
}
}
}
// create per stack ingress resources in order to have per stack
// hostnames. The ingress created will be owned by the stack and thus
// will automatically get deleted when the corresponding stack is
// deleted.
// Because of how the traffic switching works in skipper we can't just
// have a single ingress with all the hostnames, as the traffic would
// apply to all host rules, even though we don't want traffic switching
// for the per stack hostnames. For this reason we must create extra
// ingresses per stack.
for _, stack := range stacks.Items {
// don't manage ingress for terminating stack.
if stack.DeletionTimestamp != nil && stack.DeletionTimestamp.Time.Before(time.Now().UTC()) {
continue
}
err := c.stackIngress(stack)
if err != nil {
log.Error(err)
continue
}
}
return nil
}
type stackStatus struct {
Stack zv1.Stack
Available bool
}
func (c *IngressController) getStackStatuses(stacks []zv1.Stack) ([]stackStatus, error) {
statuses := make([]stackStatus, 0, len(stacks))
for _, stack := range stacks {
status := stackStatus{
Stack: stack,
}
// check that service has at least one endpoint, otherwise it
// should not get traffic.
endpoints, err := c.kube.CoreV1().Endpoints(stack.Namespace).Get(stack.Name, metav1.GetOptions{})
if err != nil {
if !errors.IsNotFound(err) {
return nil, fmt.Errorf(
"failed to get Endpoints for stack %s/%s: %v",
stack.Namespace,
stack.Name,
err,
)
}
status.Available = false
} else {
readyEndpoints := 0
for _, subset := range endpoints.Subsets {
readyEndpoints += len(subset.Addresses)
}
status.Available = readyEndpoints > 0
}
statuses = append(statuses, status)
}
return statuses, nil
}
func (c *IngressController) stackIngress(stack zv1.Stack) error {
ingress, err := ingressForStack(&c.stackset, &stack)
if err != nil {
return fmt.Errorf("failed generate Ingress for Stack %s/%s: %s", stack.Namespace, stack.Name, err)
}
ing, err := c.kube.ExtensionsV1beta1().Ingresses(ingress.Namespace).Get(ingress.Name, metav1.GetOptions{})
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("failed to get Ingress %s/%s: %s", ingress.Namespace, ingress.Name, err)
}
ing = nil
}
if ing == nil {
c.logger.Infof("Creating Ingress %s/%s", ingress.Namespace, ingress.Name)
_, err := c.kube.ExtensionsV1beta1().Ingresses(ingress.Namespace).Create(ingress)
if err != nil {
return fmt.Errorf("failed to create Ingress %s/%s: %s", ingress.Namespace, ingress.Name, err)
}
} else {
// check if ingress is already owned by a different resource.
if !isOwnedReference(stack.TypeMeta, stack.ObjectMeta, ing.ObjectMeta) {
return fmt.Errorf("Ingress %s/%s already has a different owner: %v", ing.Namespace, ing.Name, ing.ObjectMeta.OwnerReferences)
}
// add objectMeta from existing ingress
ingress.SelfLink = ing.SelfLink
ingress.UID = ing.UID
ingress.Generation = ing.Generation
ingress.CreationTimestamp = ing.CreationTimestamp
ingress.ResourceVersion = ing.ResourceVersion
ing.Status = v1beta1.IngressStatus{}
if !reflect.DeepEqual(ing, ingress) {
c.logger.Debugf("Ingress %s/%s changed: %s", ingress.Namespace, ingress.Name, cmp.Diff(ing, ingress))
c.logger.Infof("Updating Ingress %s/%s.", ingress.Namespace, ingress.Name)
_, err := c.kube.ExtensionsV1beta1().Ingresses(ingress.Namespace).Update(ingress)
if err != nil {
return fmt.Errorf("failed to update Ingress %s/%s: %v", ingress.Namespace, ingress.Name, err)
}
}
}
return nil
}
func (c *IngressController) gcStackIngress(stack zv1.Stack) error {
ing, err := c.kube.ExtensionsV1beta1().Ingresses(stack.Namespace).Get(stack.Name, metav1.GetOptions{})
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("failed to get Ingress %s/%s: %s", stack.Namespace, stack.Name, err)
}
return nil
}
// check if ingress is already owned by a different resource.
if !isOwnedReference(stack.TypeMeta, stack.ObjectMeta, ing.ObjectMeta) {
return fmt.Errorf("Ingress %s/%s already has a different owner: %v", ing.Namespace, ing.Name, ing.ObjectMeta.OwnerReferences)
}
c.logger.Infof("Deleting obsolete Ingress %s/%s.", ing.Namespace, ing.Name)
err = c.kube.ExtensionsV1beta1().Ingresses(ing.Namespace).Delete(ing.Name, nil)
if err != nil {
return fmt.Errorf("failed to delete Ingress %s/%s: %v", ing.Namespace, ing.Name, err)
}
return nil
}
// ingressForStack generates an ingress object based on a stack.
func ingressForStack(stackset *zv1.StackSet, stack *zv1.Stack) (*v1beta1.Ingress, error) {
ingress := &v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: stack.Name,
Namespace: stack.Namespace,
Labels: stack.Labels,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: stack.APIVersion,
Kind: stack.Kind,
Name: stack.Name,
UID: stack.UID,
},
},
},
Spec: v1beta1.IngressSpec{
Rules: make([]v1beta1.IngressRule, 0),
},
}
if stackset.Spec.Ingress.Annotations != nil {
ingress.Annotations = map[string]string{}
}
// insert annotations
for k, v := range stackset.Spec.Ingress.Annotations {
ingress.Annotations[k] = v
}
rule := v1beta1.IngressRule{
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: make([]v1beta1.HTTPIngressPath, 0),
},
},
}
path := v1beta1.HTTPIngressPath{
Path: "", // TODO: support paths
Backend: v1beta1.IngressBackend{
ServiceName: stack.Name,
ServicePort: intstr.FromString(ingressPortName), // TODO: find a better way for service port mapping.
},
}
rule.IngressRuleValue.HTTP.Paths = append(rule.IngressRuleValue.HTTP.Paths, path)
// create rule per hostname
for _, host := range stackset.Spec.Ingress.Hosts {
r := rule
newHost, err := createSubdomain(host, stack.Name)
if err != nil {
return nil, fmt.Errorf("failed to create domain name: %s", err)
}
r.Host = newHost
ingress.Spec.Rules = append(ingress.Spec.Rules, r)
}
return ingress, nil
}
// ingressForStackSet
func ingressForStackSet(stackset *zv1.StackSet, origIngress *v1beta1.Ingress, stackStatuses []stackStatus) (*v1beta1.Ingress, error) {
heritageLabels := map[string]string{
stacksetHeritageLabelKey: stackset.Name,
}
labels := mergeLabels(
heritageLabels,
stackset.Labels,
)
ingress := &v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: stackset.Name,
Namespace: stackset.Namespace,
Labels: labels,
Annotations: map[string]string{},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: stackset.APIVersion,
Kind: stackset.Kind,
Name: stackset.Name,
UID: stackset.UID,
},
},
},
Spec: v1beta1.IngressSpec{
Rules: make([]v1beta1.IngressRule, 0),
},
}
// insert annotations
for k, v := range stackset.Spec.Ingress.Annotations {
ingress.Annotations[k] = v
}
// set ObjectMeta from the exisiting ingress resource
// this is done to ensure we only update the resource if something
// changes.
if origIngress != nil {
ingress.SelfLink = origIngress.SelfLink
ingress.UID = origIngress.UID
ingress.Generation = origIngress.Generation
ingress.CreationTimestamp = origIngress.CreationTimestamp
ingress.ResourceVersion = origIngress.ResourceVersion
}
rule := v1beta1.IngressRule{
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: make([]v1beta1.HTTPIngressPath, 0),
},
},
}
// get current stack traffic weights stored on ingress.
currentWeights := make(map[string]float64, len(stackStatuses))
if origIngress != nil {
if weights, ok := origIngress.Annotations[stackTrafficWeightsAnnotationKey]; ok {
err := json.Unmarshal([]byte(weights), ¤tWeights)
if err != nil {
return nil, fmt.Errorf("failed to get current Stack traffic weights: %v", err)
}
}
}
availableWeights, allWeights := computeBackendWeights(stackStatuses, currentWeights)
for backend, traffic := range availableWeights {
if traffic > 0 {
path := v1beta1.HTTPIngressPath{
Path: "", // TODO: support paths
Backend: v1beta1.IngressBackend{
ServiceName: backend,
ServicePort: intstr.FromString(ingressPortName), // TODO: find a better way for service port mapping.
},
}
rule.IngressRuleValue.HTTP.Paths = append(rule.IngressRuleValue.HTTP.Paths, path)
}
}
// sort backends by name to have a consitent generated ingress
// resource.
sort.Slice(rule.IngressRuleValue.HTTP.Paths, func(i, j int) bool {
return rule.IngressRuleValue.HTTP.Paths[i].Backend.ServiceName < rule.IngressRuleValue.HTTP.Paths[j].Backend.ServiceName
})
// create rule per hostname
for _, host := range stackset.Spec.Ingress.Hosts {
r := rule
r.Host = host
ingress.Spec.Rules = append(ingress.Spec.Rules, r)
}
availableWeightsData, err := json.Marshal(&availableWeights)
if err != nil {
return nil, err
}
allWeightsData, err := json.Marshal(&allWeights)
if err != nil {
return nil, err
}
if ingress.Annotations == nil {
ingress.Annotations = map[string]string{}
}
ingress.Annotations[backendWeightsAnnotationKey] = string(availableWeightsData)
ingress.Annotations[stackTrafficWeightsAnnotationKey] = string(allWeightsData)
return ingress, nil
}
// allZero returns true if all weights defined in the map are 0.
func allZero(weights map[string]float64) bool {
for _, weight := range weights {
if weight > 0 {
return false
}
}
return true
}
// normalizeWeights normalizes a map of backend weights.
// If all weights are zero the total weight of 100 is distributed equally
// between all backends.
// If not all weights are zero they are normalized to a sum of 100.
// Note this modifies the passed map inplace instead of returning a modified
// copy.
func normalizeWeights(backendWeights map[string]float64) {
// if all weights are zero distribute them equally to all backends
if allZero(backendWeights) && len(backendWeights) > 0 {
eqWeight := 100 / float64(len(backendWeights))
for backend := range backendWeights {
backendWeights[backend] = eqWeight
}
return
}
// if not all weights are zero, normalize them to a sum of 100
sum := float64(0)
for _, weight := range backendWeights {
sum += weight
}
for backend, weight := range backendWeights {
backendWeights[backend] = weight / sum * 100
}
}
func computeBackendWeights(stacks []stackStatus, traffic map[string]float64) (map[string]float64, map[string]float64) {
backendWeights := make(map[string]float64, len(stacks))
availableBackends := make(map[string]float64, len(stacks))
for _, stack := range stacks {
backendWeights[stack.Stack.Name] = traffic[stack.Stack.Name]
if stack.Available {
availableBackends[stack.Stack.Name] = traffic[stack.Stack.Name]
}
}
// TODO: validate this logic
if !allZero(backendWeights) {
normalizeWeights(backendWeights)
}
if len(availableBackends) == 0 {
availableBackends = backendWeights
}
// TODO: think of case were all are zero and the service/deployment is
// deleted.
normalizeWeights(availableBackends)
return availableBackends, backendWeights
}
func getIngress(client kubernetes.Interface, stackset *zv1.StackSet) (*v1beta1.Ingress, error) {
// check for existing ingress object
ing, err := client.ExtensionsV1beta1().Ingresses(stackset.Namespace).Get(stackset.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
// check if ingress is owned by the stackset resource
if !isOwnedReference(stackset.TypeMeta, stackset.ObjectMeta, ing.ObjectMeta) {
return nil, fmt.Errorf(
"found Ingress '%s/%s' not managed by the StackSet %s/%s",
ing.Namespace,
ing.Name,
stackset.Namespace,
stackset.Name,
)
}
return ing, nil
}
// isOwnedReference returns true of the dependent object is owned by the owner
// object.
func isOwnedReference(ownerTypeMeta metav1.TypeMeta, ownerObjectMeta, dependent metav1.ObjectMeta) bool {
for _, ref := range dependent.OwnerReferences {
if ref.APIVersion == ownerTypeMeta.APIVersion &&
ref.Kind == ownerTypeMeta.Kind &&
ref.UID == ownerObjectMeta.UID &&
ref.Name == ownerObjectMeta.Name {
return true
}
}
return false
}
// createSubdomain creates a subdomain giving an existing domain by replacing
// the first section of the domain. E.g. given the domain: my-app.example.org
// and the subdomain part my-new-app the resulting domain will be
// my-new-app.example.org.
func createSubdomain(domain, subdomain string) (string, error) {
names := strings.SplitN(domain, ".", 2)
if len(names) != 2 {
return "", fmt.Errorf("unexpected domain format: %s", domain)
}
names[0] = subdomain
return strings.Join(names, "."), nil
}