-
Notifications
You must be signed in to change notification settings - Fork 850
/
istio.go
1565 lines (1393 loc) · 55.4 KB
/
istio.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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package istio
import (
"context"
"encoding/json"
"fmt"
"strings"
replicasetutil "github.com/argoproj/argo-rollouts/utils/replicaset"
"github.com/mitchellh/mapstructure"
appsv1 "k8s.io/api/apps/v1"
"github.com/argoproj/argo-rollouts/rollout/trafficrouting"
jsonpatch "github.com/evanphx/json-patch/v5"
log "github.com/sirupsen/logrus"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamiclister"
"github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
evalUtils "github.com/argoproj/argo-rollouts/utils/evaluate"
istioutil "github.com/argoproj/argo-rollouts/utils/istio"
logutil "github.com/argoproj/argo-rollouts/utils/log"
"github.com/argoproj/argo-rollouts/utils/record"
)
const Http = "http"
const Tls = "tls"
const Tcp = "tcp"
const Type = "Istio"
const SpecHttpNotFound = "spec.http not found"
// NewReconciler returns a reconciler struct that brings the Virtual Service into the desired state
func NewReconciler(r *v1alpha1.Rollout, client dynamic.Interface, recorder record.EventRecorder, virtualServiceLister, destinationRuleLister dynamiclister.Lister, replicaSets []*appsv1.ReplicaSet) *Reconciler {
return &Reconciler{
rollout: r,
log: logutil.WithRollout(r),
client: client,
recorder: recorder,
virtualServiceLister: virtualServiceLister,
destinationRuleLister: destinationRuleLister,
replicaSets: replicaSets,
}
}
// Reconciler holds required fields to reconcile Istio resources
type Reconciler struct {
rollout *v1alpha1.Rollout
log *log.Entry
client dynamic.Interface
recorder record.EventRecorder
virtualServiceLister dynamiclister.Lister
destinationRuleLister dynamiclister.Lister
replicaSets []*appsv1.ReplicaSet
}
type virtualServicePatch struct {
routeIndex int
routeType string
destinationIndex int
weight int64
host string
toDelete bool
}
type virtualServicePatches []virtualServicePatch
type svcSubsets struct {
canarySvc string
stableSvc string
canarySubset string
stableSubset string
}
const (
invalidCasting = "Invalid casting: field '%s' is not of type '%s'"
)
func (patches virtualServicePatches) patchVirtualService(httpRoutes []any, tlsRoutes []any, tcpRoutes []any) error {
for _, patch := range patches {
var route map[string]any
err := false
if patch.routeType == Http {
route, err = httpRoutes[patch.routeIndex].(map[string]any)
} else if patch.routeType == Tls {
route, err = tlsRoutes[patch.routeIndex].(map[string]any)
} else if patch.routeType == Tcp {
route, err = tcpRoutes[patch.routeIndex].(map[string]any)
}
if !err {
return fmt.Errorf(invalidCasting, patch.routeType+"[]", "map[string]interface")
}
destinations, ok := route["route"].([]any)
if !ok {
return fmt.Errorf(invalidCasting, patch.routeType+"[].route", "[]interface")
}
if patch.destinationIndex < len(destinations) {
destination, ok := destinations[patch.destinationIndex].(map[string]any)
if !ok {
return fmt.Errorf(invalidCasting, patch.routeType+"[].route[].destination", "map[string]interface")
}
if patch.toDelete {
destinations = append(destinations[:patch.destinationIndex], destinations[patch.destinationIndex+1:]...)
} else {
destination["weight"] = float64(patch.weight)
destinations[patch.destinationIndex] = destination
}
route["route"] = destinations
} else {
destination := make(map[string]any, 0)
destination["weight"] = float64(patch.weight)
destination["destination"] = map[string]any{"host": patch.host}
destinations = append(destinations, destination)
route["route"] = destinations
}
if patch.routeType == Http {
httpRoutes[patch.routeIndex] = route
} else if patch.routeType == Tls {
tlsRoutes[patch.routeIndex] = route
} else if patch.routeType == Tcp {
tcpRoutes[patch.routeIndex] = route
}
}
return nil
}
func (r *Reconciler) generateVirtualServicePatches(rolloutVsvcRouteNames []string, httpRoutes []VirtualServiceHTTPRoute, rolloutVsvcTLSRoutes []v1alpha1.TLSRoute, tlsRoutes []VirtualServiceTLSRoute, rolloutVsvcTCPRoutes []v1alpha1.TCPRoute, tcpRoutes []VirtualServiceTCPRoute, desiredWeight int64, additionalDestinations ...v1alpha1.WeightDestination) virtualServicePatches {
stableSvc, canarySvc := trafficrouting.GetStableAndCanaryServices(r.rollout, false)
canarySubset := ""
stableSubset := ""
if r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule != nil {
canarySubset = r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule.CanarySubsetName
stableSubset = r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule.StableSubsetName
}
// Go through all the routes on the Istio Virtual Service looking for routes that are Istio mirror routes as well as on the
// managedRoutes field on the rollout object so that we can update the Istio mirror upon set weight calls
if r.rollout.Spec.Strategy.Canary.TrafficRouting != nil && r.rollout.Spec.Strategy.Canary.TrafficRouting.ManagedRoutes != nil {
for _, httpRoute := range httpRoutes {
if httpRoute.Mirror != nil {
for _, managedRoute := range r.rollout.Spec.Strategy.Canary.TrafficRouting.ManagedRoutes {
//Make sure we only add mirror routes from the managedRoutes field to the list of routes to update for setWeight
if managedRoute.Name == httpRoute.Name {
rolloutVsvcRouteNames = append(rolloutVsvcRouteNames, httpRoute.Name)
}
}
}
}
}
// err can be ignored because we already called ValidateHTTPRoutes earlier
httpRouteIndexesToPatch, _ := getHttpRouteIndexesToPatch(rolloutVsvcRouteNames, httpRoutes)
tlsRouteIndexesToPatch, _ := getTlsRouteIndexesToPatch(rolloutVsvcTLSRoutes, tlsRoutes)
tcpRouteIndexesToPatch, _ := getTcpRouteIndexesToPatch(rolloutVsvcTCPRoutes, tcpRoutes)
patches := virtualServicePatches{}
svcSubsets := svcSubsets{
canarySvc: canarySvc,
stableSvc: stableSvc,
canarySubset: canarySubset,
stableSubset: stableSubset,
}
// Process HTTP Routes
for _, routeIdx := range httpRouteIndexesToPatch {
if len(httpRoutes) <= routeIdx {
break
}
patches = processRoutes(Http, routeIdx, httpRoutes[routeIdx].Route, desiredWeight, svcSubsets, patches, additionalDestinations...)
}
// Process TLS Routes
for _, routeIdx := range tlsRouteIndexesToPatch {
if len(tlsRoutes) <= routeIdx {
break
}
patches = processRoutes(Tls, routeIdx, tlsRoutes[routeIdx].Route, desiredWeight, svcSubsets, patches, additionalDestinations...)
}
// Process TCP Routes
for _, routeIdx := range tcpRouteIndexesToPatch {
if len(tcpRoutes) <= routeIdx {
break
}
patches = processRoutes(Tcp, routeIdx, tcpRoutes[routeIdx].Route, desiredWeight, svcSubsets, patches, additionalDestinations...)
}
return patches
}
func processRoutes(routeType string, routeIdx int, destinations []VirtualServiceRouteDestination, desiredWeight int64, svcSubsets svcSubsets, patches virtualServicePatches, additionalDestinations ...v1alpha1.WeightDestination) virtualServicePatches {
svcToDest := map[string]v1alpha1.WeightDestination{}
stableWeight := 100 - desiredWeight
for _, dest := range additionalDestinations {
svcToDest[dest.ServiceName] = dest
stableWeight -= int64(dest.Weight)
}
for idx, destination := range destinations {
host := getHost(destination)
subset := destination.Destination.Subset
weight := destination.Weight
if host != "" {
if host == svcSubsets.canarySvc || (subset != "" && subset == svcSubsets.canarySubset) {
patches = appendPatch(routeIdx, routeType, weight, desiredWeight, idx, host, false, patches)
} else if host == svcSubsets.stableSvc || (subset != "" && subset == svcSubsets.stableSubset) {
patches = appendPatch(routeIdx, routeType, weight, stableWeight, idx, host, false, patches)
} else if dest, ok := svcToDest[host]; ok { // Patch weight for existing experiment services
patches = appendPatch(routeIdx, routeType, weight, int64(dest.Weight), idx, host, false, patches)
delete(svcToDest, host)
} else {
patches = appendPatch(routeIdx, routeType, weight, 0, idx, host, true, patches)
}
}
}
// Add new destinations for experiment services which don't exist yet
idx := len(destinations)
for _, dest := range svcToDest {
patches = appendPatch(routeIdx, routeType, 0, int64(dest.Weight), idx, dest.ServiceName, false, patches)
idx += 1
}
return patches
}
func getHost(destination VirtualServiceRouteDestination) string {
var host string
if idx := strings.Index(destination.Destination.Host, "."); idx > 0 {
host = destination.Destination.Host[:idx]
} else if idx < 0 {
host = destination.Destination.Host
}
return host
}
func appendPatch(routeIdx int, routeType string, weight int64, desiredWeight int64, destinationIndex int, host string, toDelete bool, patches virtualServicePatches) virtualServicePatches {
if weight != desiredWeight {
patch := virtualServicePatch{
routeIndex: routeIdx,
routeType: routeType,
destinationIndex: destinationIndex,
weight: desiredWeight,
host: host,
toDelete: toDelete,
}
patches = append(patches, patch)
}
return patches
}
func (r *Reconciler) reconcileVirtualService(obj *unstructured.Unstructured, vsvcRouteNames []string, vsvcTLSRoutes []v1alpha1.TLSRoute, vsvcTCPRoutes []v1alpha1.TCPRoute, desiredWeight int32, additionalDestinations ...v1alpha1.WeightDestination) (*unstructured.Unstructured, bool, error) {
newObj := obj.DeepCopy()
// HTTP Routes
var httpRoutes []VirtualServiceHTTPRoute
httpRoutesI, err := GetHttpRoutesI(newObj)
if err == nil {
httpRoutes, err = GetHttpRoutes(httpRoutesI)
if err != nil {
return nil, false, err
}
if err = ValidateHTTPRoutes(r.rollout, vsvcRouteNames, httpRoutes); err != nil {
return nil, false, err
}
}
// TLS Routes
var tlsRoutes []VirtualServiceTLSRoute
tlsRoutesI, err := GetTlsRoutesI(newObj)
if err == nil {
tlsRoutes, err = GetTlsRoutes(newObj, tlsRoutesI)
if err != nil {
return nil, false, err
}
if err = ValidateTlsRoutes(r.rollout, vsvcTLSRoutes, tlsRoutes); err != nil {
return nil, false, err
}
}
// TCP Routes
var tcpRoutes []VirtualServiceTCPRoute
tcpRoutesI, err := GetTcpRoutesI(newObj)
if err == nil {
tcpRoutes, err = GetTcpRoutes(newObj, tcpRoutesI)
if err != nil {
return nil, false, err
}
if err = ValidateTcpRoutes(r.rollout, vsvcTCPRoutes, tcpRoutes); err != nil {
return nil, false, err
}
}
// Generate Patches
patches := r.generateVirtualServicePatches(vsvcRouteNames, httpRoutes, vsvcTLSRoutes, tlsRoutes, vsvcTCPRoutes, tcpRoutes, int64(desiredWeight), additionalDestinations...)
err = patches.patchVirtualService(httpRoutesI, tlsRoutesI, tcpRoutesI)
if err != nil {
return nil, false, err
}
// Set HTTP Route Slice
if len(httpRoutes) > 0 {
if err := unstructured.SetNestedSlice(newObj.Object, httpRoutesI, "spec", Http); err != nil {
return newObj, len(patches) > 0, err
}
}
// Set TLS Route Slice
if len(tlsRoutes) > 0 {
err = unstructured.SetNestedSlice(newObj.Object, tlsRoutesI, "spec", Tls)
if err != nil {
return newObj, len(patches) > 0, err
}
}
// Set TCP Route Slice
if len(tcpRoutes) > 0 {
err = unstructured.SetNestedSlice(newObj.Object, tcpRoutesI, "spec", Tcp)
}
return newObj, len(patches) > 0, err
}
func (r *Reconciler) UpdateHash(canaryHash, stableHash string, additionalDestinations ...v1alpha1.WeightDestination) error {
// We need to check if the replicasets are ready here as well if we didn't define any services in the rollout
// See: https://github.com/argoproj/argo-rollouts/issues/2507
if r.rollout.Spec.Strategy.Canary.CanaryService == "" && r.rollout.Spec.Strategy.Canary.StableService == "" {
for _, rs := range r.replicaSets {
if *rs.Spec.Replicas > 0 && !replicasetutil.IsReplicaSetAvailable(rs) {
return fmt.Errorf("delaying destination rule switch: ReplicaSet %s not fully available", rs.Name)
}
}
}
dRuleSpec := r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule
if dRuleSpec == nil {
return nil
}
ctx := context.TODO()
client := r.client.Resource(istioutil.GetIstioDestinationRuleGVR()).Namespace(r.rollout.Namespace)
origBytes, dRule, dRuleNew, err := r.getDestinationRule(dRuleSpec, client, ctx)
if err != nil {
return err
}
if dRuleNew.Annotations == nil {
dRuleNew.Annotations = make(map[string]string)
}
dRuleNew.Annotations[v1alpha1.ManagedByRolloutsKey] = r.rollout.Name
// Maps service to WeightDestination object
svcToDest := map[string]v1alpha1.WeightDestination{}
for _, dest := range additionalDestinations {
svcToDest[dest.ServiceName] = dest
}
tmp := make([]Subset, 0)
for _, subset := range dRuleNew.Spec.Subsets {
if subset.Name == dRuleSpec.CanarySubsetName { // Canary Subset
if subset.Labels == nil {
subset.Labels = make(map[string]string)
}
if canaryHash != "" {
subset.Labels[v1alpha1.DefaultRolloutUniqueLabelKey] = canaryHash
} else {
delete(subset.Labels, v1alpha1.DefaultRolloutUniqueLabelKey)
}
} else if subset.Name == dRuleSpec.StableSubsetName { // Stable Subset
if subset.Labels == nil {
subset.Labels = make(map[string]string)
}
if stableHash != "" {
subset.Labels[v1alpha1.DefaultRolloutUniqueLabelKey] = stableHash
} else {
delete(subset.Labels, v1alpha1.DefaultRolloutUniqueLabelKey)
}
} else if dest, ok := svcToDest[subset.Name]; ok { // Current experiment steps
if dest.PodTemplateHash != "" {
subset.Labels[v1alpha1.DefaultRolloutUniqueLabelKey] = dest.PodTemplateHash
delete(svcToDest, subset.Name)
} else {
delete(subset.Labels, v1alpha1.DefaultRolloutUniqueLabelKey)
}
} else {
continue // Ignore any extraneous subsets (not stable, canary, or additionalDestination)
}
tmp = append(tmp, subset)
}
dRuleNew.Spec.Subsets = tmp
// Add new subsets for experiment services if they don't exist yet
for _, dest := range svcToDest {
dRuleNew.Spec.Subsets = append(dRuleNew.Spec.Subsets, Subset{
Name: dest.ServiceName,
Labels: map[string]string{v1alpha1.DefaultRolloutUniqueLabelKey: dest.PodTemplateHash},
})
}
modified, err := updateDestinationRule(ctx, client, origBytes, dRule, dRuleNew)
if err != nil {
return err
}
if modified {
r.recorder.Eventf(r.rollout, record.EventOptions{EventReason: "UpdatedDestinationRule"},
"DestinationRule %s subset updated (%s: %s, %s: %s)", dRuleSpec.Name, dRuleSpec.CanarySubsetName, canaryHash, dRuleSpec.StableSubsetName, stableHash)
}
return nil
}
// destinationRuleReplaceExtraMarshal relace the key of "Extra" with the actual content
// e.g., "trafficpolicy" and return the bytes of the new object
func destinationRuleReplaceExtraMarshal(dRule *DestinationRule) []byte {
dRuleNew := map[string]any{}
dRuleNew["metadata"] = dRule.ObjectMeta.DeepCopy()
subsets := []map[string]any{}
for _, subset := range dRule.Spec.Subsets {
newsubset := map[string]any{}
newsubset["name"] = subset.Name
newsubset["labels"] = subset.Labels
if subset.Extra == nil {
subsets = append(subsets, newsubset)
continue
}
extra := map[string]any{}
inputbyte, _ := json.Marshal(subset.Extra)
json.Unmarshal(inputbyte, &extra)
subset.Extra = nil
for k, v := range extra {
newsubset[k] = v
}
subsets = append(subsets, newsubset)
}
dRuleNew["spec"] = map[string]any{
"subsets": subsets,
"host": dRule.Spec.Host,
}
dRuleNewBytes, _ := json.Marshal(dRuleNew)
return dRuleNewBytes
}
func updateDestinationRule(ctx context.Context, client dynamic.ResourceInterface, orig []byte, dRule, dRuleNew *DestinationRule) (bool, error) {
dRuleBytes, err := json.Marshal(dRule)
if err != nil {
return false, err
}
dRuleNewBytes := destinationRuleReplaceExtraMarshal(dRuleNew)
log.Debugf("dRuleNewBytes: %s", string(dRuleNewBytes))
patch, err := jsonpatch.CreateMergePatch(dRuleBytes, dRuleNewBytes)
if err != nil {
return false, err
}
if string(patch) == "{}" {
return false, nil
}
dRuleNewBytes, err = jsonpatch.MergePatch(orig, patch)
if err != nil {
return false, err
}
var newDRuleUn unstructured.Unstructured
err = json.Unmarshal(dRuleNewBytes, &newDRuleUn.Object)
if err != nil {
return false, err
}
_, err = client.Update(ctx, &newDRuleUn, metav1.UpdateOptions{})
if err != nil {
return false, err
}
log.Infof("updating destinationrule: %s", string(patch))
return true, nil
}
// unstructuredToDestinationRules is a helper which returns two instances of DestinationRule
// from an unstructured object. The two copies are used to calculate patches.
func unstructuredToDestinationRules(un *unstructured.Unstructured) ([]byte, *DestinationRule, *DestinationRule, error) {
dRuleBytes, err := json.Marshal(un)
if err != nil {
return nil, nil, nil, err
}
dRule1, err := jsonBytesToDestinationRule(dRuleBytes)
if err != nil {
return nil, nil, nil, err
}
dRule2, err := jsonBytesToDestinationRule(dRuleBytes)
if err != nil {
return nil, nil, nil, err
}
return dRuleBytes, dRule1, dRule2, nil
}
func unMarshalSubsets(dRule *DestinationRule, dRuleBytes []byte) error {
var err error
unstructured := map[string]any{}
var extractFieldBytes func([]byte, string) ([]byte, error)
extractFieldBytes = func(input []byte, name string) ([]byte, error) {
err = json.Unmarshal(input, &unstructured)
if err != nil {
return nil, err
}
fieldBytes, err := json.Marshal(unstructured[name])
if err != nil {
return nil, err
}
return fieldBytes, nil
}
specBytes, err := extractFieldBytes(dRuleBytes, "spec")
if err != nil {
return err
}
subsetsBytes, err := extractFieldBytes(specBytes, "subsets")
if err != nil {
return err
}
subsetsMap := []map[string]any{}
err = json.Unmarshal(subsetsBytes, &subsetsMap)
if err != nil {
return err
}
dRule.Spec.Subsets = []Subset{}
for _, si := range subsetsMap {
var subset Subset
jsonInput, _ := json.Marshal(si)
extra, err := UnmarshalJson(jsonInput, &subset)
if err != nil {
return err
}
subset.Extra = extra
if len(subset.Extra) == 0 {
subset.Extra = nil
}
dRule.Spec.Subsets = append(dRule.Spec.Subsets, subset)
}
return nil
}
func UnmarshalJson(input []byte, result any) (map[string]any, error) {
// unmarshal json to a map
foomap := make(map[string]any)
json.Unmarshal(input, &foomap)
// create a mapstructure decoder
var md mapstructure.Metadata
decoder, err := mapstructure.NewDecoder(
&mapstructure.DecoderConfig{
Metadata: &md,
Result: result,
})
if err != nil {
return nil, err
}
// decode the unmarshalled map into the given struct
if err := decoder.Decode(foomap); err != nil {
return nil, err
}
// copy and return unused fields
unused := map[string]any{}
for _, k := range md.Unused {
unused[k] = foomap[k]
}
return unused, nil
}
func jsonBytesToDestinationRule(dRuleBytes []byte) (*DestinationRule, error) {
var dRule DestinationRule
err := json.Unmarshal(dRuleBytes, &dRule)
if err != nil {
return nil, err
}
err = unMarshalSubsets(&dRule, dRuleBytes)
if err != nil {
return nil, err
}
return &dRule, nil
}
func GetHttpRoutesI(obj *unstructured.Unstructured) ([]any, error) {
httpRoutesI, notFound, err := unstructured.NestedSlice(obj.Object, "spec", Http)
if !notFound {
return nil, fmt.Errorf(SpecHttpNotFound)
}
if err != nil {
return nil, err
}
return httpRoutesI, nil
}
func GetTlsRoutesI(obj *unstructured.Unstructured) ([]any, error) {
tlsRoutesI, notFound, err := unstructured.NestedSlice(obj.Object, "spec", Tls)
if !notFound {
return nil, fmt.Errorf(SpecHttpNotFound)
}
if err != nil {
return nil, err
}
return tlsRoutesI, nil
}
func GetTcpRoutesI(obj *unstructured.Unstructured) ([]any, error) {
tcpRoutesI, notFound, err := unstructured.NestedSlice(obj.Object, "spec", Tcp)
if !notFound {
return nil, fmt.Errorf(".spec.tcp is not defined")
}
if err != nil {
return nil, err
}
return tcpRoutesI, nil
}
func GetHttpRoutes(httpRoutesI []any) ([]VirtualServiceHTTPRoute, error) {
routeBytes, err := json.Marshal(httpRoutesI)
if err != nil {
return nil, err
}
var httpRoutes []VirtualServiceHTTPRoute
err = json.Unmarshal(routeBytes, &httpRoutes)
if err != nil {
return nil, err
}
return httpRoutes, nil
}
func GetTlsRoutes(obj *unstructured.Unstructured, tlsRoutesI []any) ([]VirtualServiceTLSRoute, error) {
routeBytes, err := json.Marshal(tlsRoutesI)
if err != nil {
return nil, err
}
var tlsRoutes []VirtualServiceTLSRoute
err = json.Unmarshal(routeBytes, &tlsRoutes)
if err != nil {
return nil, err
}
return tlsRoutes, nil
}
func GetTcpRoutes(obj *unstructured.Unstructured, tcpRoutesI []any) ([]VirtualServiceTCPRoute, error) {
routeBytes, err := json.Marshal(tcpRoutesI)
if err != nil {
return nil, err
}
var tcpRoutes []VirtualServiceTCPRoute
err = json.Unmarshal(routeBytes, &tcpRoutes)
if err != nil {
return nil, err
}
return tcpRoutes, nil
}
// Type indicates this reconciler is an Istio reconciler
func (r *Reconciler) Type() string {
return Type
}
// SetWeight modifies Istio resources to reach desired state
func (r *Reconciler) SetWeight(desiredWeight int32, additionalDestinations ...v1alpha1.WeightDestination) error {
ctx := context.TODO()
virtualServices := r.getVirtualServices()
for _, virtualService := range virtualServices {
name := virtualService.Name
namespace, vsvcName := istioutil.GetVirtualServiceNamespaceName(name)
if namespace == "" {
namespace = r.rollout.Namespace
}
client := r.client.Resource(istioutil.GetIstioVirtualServiceGVR()).Namespace(namespace)
vsvc, err := r.getVirtualService(namespace, vsvcName, client, ctx)
if err != nil {
return err
}
modifiedVirtualService, modified, err := r.reconcileVirtualService(vsvc, virtualService.Routes, virtualService.TLSRoutes, virtualService.TCPRoutes, desiredWeight, additionalDestinations...)
if err != nil {
return err
}
if !modified {
continue
}
if err := r.orderRoutes(modifiedVirtualService); err != nil && err.Error() != SpecHttpNotFound {
return fmt.Errorf("[SetWeight] failed to order routes: %w", err)
}
_, err = client.Update(ctx, modifiedVirtualService, metav1.UpdateOptions{})
if err == nil {
r.log.Debugf("Updated VirtualService: %s", modifiedVirtualService)
r.recorder.Eventf(r.rollout, record.EventOptions{EventReason: "Updated VirtualService"}, "VirtualService `%s` set to desiredWeight '%d'", vsvcName, desiredWeight)
} else {
return err
}
}
return nil
}
func (r *Reconciler) getVirtualServices() []v1alpha1.IstioVirtualService {
if istioutil.MultipleVirtualServiceConfigured(r.rollout) {
return r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.VirtualServices
} else {
return []v1alpha1.IstioVirtualService{*r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.VirtualService}
}
}
func (r *Reconciler) getVirtualService(namespace string, vsvcName string, client dynamic.ResourceInterface, ctx context.Context) (*unstructured.Unstructured, error) {
var vsvc *unstructured.Unstructured
var err error
if r.virtualServiceLister != nil {
vsvc, err = r.virtualServiceLister.Namespace(namespace).Get(vsvcName)
} else {
vsvc, err = client.Get(ctx, vsvcName, metav1.GetOptions{})
}
if err != nil {
if k8serrors.IsNotFound(err) {
r.recorder.Warnf(r.rollout, record.EventOptions{EventReason: "VirtualServiceNotFound"}, "VirtualService `%s` not found", vsvcName)
}
return nil, err
}
return vsvc, err
}
func (r *Reconciler) reconcileVirtualServiceHeaderRoutes(virtualService v1alpha1.IstioVirtualService, obj *unstructured.Unstructured, headerRouting *v1alpha1.SetHeaderRoute) error {
destRuleHost, err := r.getDestinationRuleHost()
if err != nil {
return err
}
_, canarySvc := trafficrouting.GetStableAndCanaryServices(r.rollout, false)
if destRuleHost != "" {
canarySvc = destRuleHost
}
var canarySubset string
if r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule != nil {
canarySubset = r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule.CanarySubsetName
}
if headerRouting.Match == nil {
//Remove mirror route
err := removeRoute(obj, headerRouting.Name)
if err != nil {
return fmt.Errorf("[reconcileVirtualServiceHeaderRoutes] failed to remove route from virtual service: %w", err)
}
return nil
}
//Remove route first to avoid duplicates
err = removeRoute(obj, headerRouting.Name)
if err != nil {
return fmt.Errorf("[reconcileVirtualServiceHeaderRoutes] failed to remove http route from virtual service: %w", err)
}
// HTTP Routes
httpRoutesI, err := GetHttpRoutesI(obj)
if err != nil {
return err
}
httpRoutesI = append(httpRoutesI, createHeaderRoute(virtualService, obj, headerRouting, canarySvc, canarySubset))
err = unstructured.SetNestedSlice(obj.Object, httpRoutesI, "spec", Http)
if err != nil {
return err
}
return nil
}
func (r *Reconciler) SetHeaderRoute(headerRouting *v1alpha1.SetHeaderRoute) error {
ctx := context.TODO()
virtualServices := r.getVirtualServices()
for _, virtualService := range virtualServices {
name := virtualService.Name
namespace, vsvcName := istioutil.GetVirtualServiceNamespaceName(name)
if namespace == "" {
namespace = r.rollout.Namespace
}
client := r.client.Resource(istioutil.GetIstioVirtualServiceGVR()).Namespace(namespace)
vsvc, err := r.getVirtualService(namespace, vsvcName, client, ctx)
if err != nil {
return fmt.Errorf("[SetHeaderRoute] failed to get istio virtual service: %w", err)
}
err = r.reconcileVirtualServiceHeaderRoutes(virtualService, vsvc, headerRouting)
if err != nil {
return fmt.Errorf("[SetHeaderRoute] failed to reconcile header routes: %w", err)
}
if err := r.orderRoutes(vsvc); err != nil && err.Error() != SpecHttpNotFound {
return fmt.Errorf("[SetHeaderRoute] failed to order routes: %w", err)
}
_, err = client.Update(ctx, vsvc, metav1.UpdateOptions{})
if err == nil {
r.log.Debugf("Updated VirtualService: %s", vsvc)
r.recorder.Eventf(r.rollout, record.EventOptions{EventReason: "Updated VirtualService"}, "VirtualService `%s` set headerRoute '%v'", vsvcName, headerRouting.Name)
} else {
return fmt.Errorf("[SetHeaderRoute] failed to update routes: %w", err)
}
}
return nil
}
func (r *Reconciler) getDestinationRuleHost() (string, error) {
if r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule != nil {
ctx := context.TODO()
client := r.client.Resource(istioutil.GetIstioDestinationRuleGVR()).Namespace(r.rollout.Namespace)
_, dRule, _, err := r.getDestinationRule(r.rollout.Spec.Strategy.Canary.TrafficRouting.Istio.DestinationRule, client, ctx)
if err != nil {
return "", err
}
return dRule.Spec.Host, nil
}
return "", nil
}
func (r *Reconciler) getDestinationRule(dRuleSpec *v1alpha1.IstioDestinationRule, client dynamic.ResourceInterface, ctx context.Context) ([]byte, *DestinationRule, *DestinationRule, error) {
var dRuleUn *unstructured.Unstructured
var err error
if r.destinationRuleLister != nil {
dRuleUn, err = r.destinationRuleLister.Namespace(r.rollout.Namespace).Get(dRuleSpec.Name)
} else {
dRuleUn, err = client.Get(ctx, dRuleSpec.Name, metav1.GetOptions{})
}
if err != nil {
if k8serrors.IsNotFound(err) {
r.recorder.Warnf(r.rollout, record.EventOptions{EventReason: "DestinationRuleNotFound"}, "DestinationRule `%s` not found", dRuleSpec.Name)
}
return nil, nil, nil, err
}
origBytes, dRule, dRuleNew, err := unstructuredToDestinationRules(dRuleUn)
if err != nil {
return nil, nil, nil, err
}
return origBytes, dRule, dRuleNew, nil
}
func createHeaderRoute(virtualService v1alpha1.IstioVirtualService, unVsvc *unstructured.Unstructured, headerRouting *v1alpha1.SetHeaderRoute, host string, subset string) map[string]any {
var routeMatches []any
for _, hrm := range headerRouting.Match {
routeMatches = append(routeMatches, createHeaderRouteMatch(hrm))
}
port, err := getVirtualServiceCanaryPort(unVsvc, virtualService)
if err != nil {
port = Port{Number: 0}
}
canaryDestination := routeDestination(host, port.Number, subset, 100)
return map[string]any{
"name": headerRouting.Name,
"match": routeMatches,
"route": []any{canaryDestination},
}
}
func createHeaderRouteMatch(hrm v1alpha1.HeaderRoutingMatch) any {
res := map[string]any{}
value := hrm.HeaderValue
setMapValueIfNotEmpty(res, "exact", value.Exact)
setMapValueIfNotEmpty(res, "regex", value.Regex)
setMapValueIfNotEmpty(res, "prefix", value.Prefix)
return map[string]any{
"headers": map[string]any{hrm.HeaderName: res},
}
}
func setMapValueIfNotEmpty(m map[string]any, key string, value string) {
if value != "" {
m[key] = value
}
}
func routeDestination(host string, port uint32, subset string, weight int64) map[string]any {
dest := map[string]any{
"host": host,
}
if port > 0 {
dest["port"] = map[string]any{"number": int64(port)}
}
if subset != "" {
dest["subset"] = subset
}
routeValue := map[string]any{
"weight": float64(weight),
"destination": dest,
}
return routeValue
}
func (r *Reconciler) VerifyWeight(desiredWeight int32, additionalDestinations ...v1alpha1.WeightDestination) (*bool, error) {
return nil, nil
}
// getHttpRouteIndexesToPatch returns array indices of the httpRoutes which need to be patched when updating weights
func getHttpRouteIndexesToPatch(routeNames []string, httpRoutes []VirtualServiceHTTPRoute) ([]int, error) {
//We have no routes listed in spec.strategy.canary.trafficRouting.istio.virtualService.routes so find index
//of the first empty named route
if len(routeNames) == 0 {
for i, route := range httpRoutes {
if route.Name == "" {
return []int{i}, nil
}
}
}
var routeIndexesToPatch []int
for _, routeName := range routeNames {
routeIndex := searchHttpRoute(routeName, httpRoutes)
if routeIndex > -1 {
routeIndexesToPatch = append(routeIndexesToPatch, routeIndex)
} else {
return nil, fmt.Errorf("HTTP Route '%s' is not found in the defined Virtual Service.", routeName)
}
}
return routeIndexesToPatch, nil
}
func searchHttpRoute(routeName string, httpRoutes []VirtualServiceHTTPRoute) int {
for i, route := range httpRoutes {
if route.Name == routeName {
return i
}
}
return -1
}
// getTlsRouteIndexesToPatch returns array indices of the tlsRoutes which need to be patched when updating weights
func getTlsRouteIndexesToPatch(tlsRoutes []v1alpha1.TLSRoute, istioTlsRoutes []VirtualServiceTLSRoute) ([]int, error) {
if len(tlsRoutes) == 0 {
return []int{0}, nil
}
var routeIndexesToPatch []int
for _, tlsRoute := range tlsRoutes {
routeIndices := searchTlsRoute(tlsRoute, istioTlsRoutes)
if len(routeIndices) > 0 {
for _, routeIndex := range routeIndices {
routeIndexesToPatch = append(routeIndexesToPatch, routeIndex)
}
} else {
return nil, fmt.Errorf("No matching TLS routes found in the defined Virtual Service.")
}
}
return routeIndexesToPatch, nil
}
func searchTlsRoute(tlsRoute v1alpha1.TLSRoute, istioTlsRoutes []VirtualServiceTLSRoute) []int {
routeIndices := []int{}
for i, route := range istioTlsRoutes {
portsMap := make(map[int64]bool)
sniHostsMap := make(map[string]bool)
for _, routeMatch := range route.Match {
portsMap[routeMatch.Port] = true
for _, sniHost := range routeMatch.SNI {
sniHostsMap[sniHost] = true
}
}
// If there are multiple ports defined then this rules is never gonna match.
if len(portsMap) > 1 {
continue
}
// Extract the first port number from the `portsMap` if it has more than
// zero ports in it.
var port int64 = 0
for portNumber := range portsMap {
port = portNumber
}
sniHosts := []string{}
for sniHostName := range sniHostsMap {
sniHosts = append(sniHosts, sniHostName)
}
// To find a match for TLS Routes in Istio VS, we'll have to verify that:
// 1. There is exactly one port present in the `ports`;
// 2. The single port in `ports` matches with the `tlsRoute.Port`;
// 3. All the SNI hosts from a single match block in the VirtualService,
// matches exactly with what the user have defined in `tlsRoute.SNIHosts`
if port == tlsRoute.Port && evalUtils.Equal(tlsRoute.SNIHosts, sniHosts) {
routeIndices = append(routeIndices, i)
}
}
return routeIndices
}
// getTcpRouteIndexesToPatch returns array indices of the tcpRoutes which need to be patched when updating weights
func getTcpRouteIndexesToPatch(tcpRoutes []v1alpha1.TCPRoute, istioTcpRoutes []VirtualServiceTCPRoute) ([]int, error) {
if len(tcpRoutes) == 0 {
return []int{0}, nil
}
var routeIndexesToPatch []int
for _, tcpRoute := range tcpRoutes {