-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
inject.go
888 lines (779 loc) · 27.4 KB
/
inject.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
// Copyright Istio 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 inject
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
"sort"
"strconv"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
jsonpatch "github.com/evanphx/json-patch/v5"
appsv1 "k8s.io/api/apps/v1"
batch "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
yamlDecoder "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
"istio.io/api/annotation"
"istio.io/api/label"
meshconfig "istio.io/api/mesh/v1alpha1"
proxyConfig "istio.io/api/networking/v1beta1"
opconfig "istio.io/istio/operator/pkg/apis/istio/v1alpha1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pkg/config/mesh"
"istio.io/istio/pkg/log"
"istio.io/istio/tools/istio-iptables/pkg/constants"
)
// InjectionPolicy determines the policy for injecting the
// sidecar proxy into the watched namespace(s).
type InjectionPolicy string
const (
// InjectionPolicyDisabled specifies that the sidecar injector
// will not inject the sidecar into resources by default for the
// namespace(s) being watched. Resources can enable injection
// using the "sidecar.istio.io/inject" annotation with value of
// true.
InjectionPolicyDisabled InjectionPolicy = "disabled"
// InjectionPolicyEnabled specifies that the sidecar injector will
// inject the sidecar into resources by default for the
// namespace(s) being watched. Resources can disable injection
// using the "sidecar.istio.io/inject" annotation with value of
// false.
InjectionPolicyEnabled InjectionPolicy = "enabled"
)
const (
// ProxyContainerName is used by e2e integration tests for fetching logs
ProxyContainerName = "istio-proxy"
// ValidationContainerName is the name of the init container that validates
// if CNI has made the necessary changes to iptables
ValidationContainerName = "istio-validation"
// InitContainerName is the name of the init container that deploys iptables
InitContainerName = "istio-init"
// EnableCoreDumpName is the name of the init container that allows core dumps
EnableCoreDumpName = "enable-core-dump"
)
const (
// ImageTypeDebug is the suffix of the debug image.
ImageTypeDebug = "debug"
// ImageTypeDistroless is the suffix of the distroless image.
ImageTypeDistroless = "distroless"
// ImageTypeDefault is the type name of the default image, sufix is elided.
ImageTypeDefault = "default"
)
// SidecarTemplateData is the data object to which the templated
// version of `SidecarInjectionSpec` is applied.
type SidecarTemplateData struct {
TypeMeta metav1.TypeMeta
DeploymentMeta metav1.ObjectMeta
ObjectMeta metav1.ObjectMeta
Spec corev1.PodSpec
ProxyConfig *meshconfig.ProxyConfig
MeshConfig *meshconfig.MeshConfig
Values map[string]any
Revision string
ProxyImage string
ProxyUID int64
ProxyGID int64
}
type (
Template *corev1.Pod
RawTemplates map[string]string
Templates map[string]*template.Template
)
type Injector interface {
Inject(pod *corev1.Pod, namespace string) ([]byte, error)
}
// Config specifies the sidecar injection configuration This includes
// the sidecar template and cluster-side injection policy. It is used
// by kube-inject, sidecar injector, and http endpoint.
type Config struct {
Policy InjectionPolicy `json:"policy"`
// DefaultTemplates defines the default template to use for pods that do not explicitly specify a template
DefaultTemplates []string `json:"defaultTemplates"`
// RawTemplates defines a set of templates to be used. The specified template will be run, provided with
// SidecarTemplateData, and merged with the original pod spec using a strategic merge patch.
RawTemplates RawTemplates `json:"templates"`
// Aliases defines a translation of a name to inject template. For example, `sidecar: [proxy,init]` could allow
// referencing two templates, "proxy" and "init" by a single name, "sidecar".
// Expansion is not recursive.
Aliases map[string][]string `json:"aliases"`
// NeverInjectSelector: Refuses the injection on pods whose labels match this selector.
// It's an array of label selectors, that will be OR'ed, meaning we will iterate
// over it and stop at the first match
// Takes precedence over AlwaysInjectSelector.
NeverInjectSelector []metav1.LabelSelector `json:"neverInjectSelector"`
// AlwaysInjectSelector: Forces the injection on pods whose labels match this selector.
// It's an array of label selectors, that will be OR'ed, meaning we will iterate
// over it and stop at the first match
AlwaysInjectSelector []metav1.LabelSelector `json:"alwaysInjectSelector"`
// InjectedAnnotations are additional annotations that will be added to the pod spec after injection
// This is primarily to support PSP annotations.
InjectedAnnotations map[string]string `json:"injectedAnnotations"`
// Templates is a pre-parsed copy of RawTemplates
Templates Templates `json:"-"`
}
const (
SidecarTemplateName = "sidecar"
)
// UnmarshalConfig unmarshals the provided YAML configuration, while normalizing the resulting configuration
func UnmarshalConfig(yml []byte) (Config, error) {
var injectConfig Config
if err := yaml.Unmarshal(yml, &injectConfig); err != nil {
return injectConfig, fmt.Errorf("failed to unmarshal injection template: %v", err)
}
if injectConfig.RawTemplates == nil {
injectConfig.RawTemplates = make(map[string]string)
}
if len(injectConfig.DefaultTemplates) == 0 {
injectConfig.DefaultTemplates = []string{SidecarTemplateName}
}
if len(injectConfig.RawTemplates) == 0 {
log.Warnf("injection templates are empty." +
" This may be caused by using an injection template from an older version of Istio." +
" Please ensure the template is correct; mismatch template versions can lead to unexpected results, including pods not being injected.")
}
var err error
injectConfig.Templates, err = ParseTemplates(injectConfig.RawTemplates)
if err != nil {
return injectConfig, err
}
return injectConfig, nil
}
func injectRequired(ignored []string, config *Config, podSpec *corev1.PodSpec, metadata metav1.ObjectMeta) bool { // nolint: lll
// Skip injection when host networking is enabled. The problem is
// that the iptables changes are assumed to be within the pod when,
// in fact, they are changing the routing at the host level. This
// often results in routing failures within a node which can
// affect the network provider within the cluster causing
// additional pod failures.
if podSpec.HostNetwork {
return false
}
// skip special kubernetes system namespaces
for _, namespace := range ignored {
if metadata.Namespace == namespace {
return false
}
}
annos := metadata.GetAnnotations()
var useDefault bool
var inject bool
objectSelector := annos[annotation.SidecarInject.Name]
if lbl, labelPresent := metadata.GetLabels()[label.SidecarInject.Name]; labelPresent {
// The label is the new API; if both are present we prefer the label
objectSelector = lbl
}
switch strings.ToLower(objectSelector) {
// http://yaml.org/type/bool.html
case "y", "yes", "true", "on":
inject = true
case "":
useDefault = true
}
// If an annotation is not explicitly given, check the LabelSelectors, starting with NeverInject
if useDefault {
for _, neverSelector := range config.NeverInjectSelector {
selector, err := metav1.LabelSelectorAsSelector(&neverSelector)
if err != nil {
log.Warnf("Invalid selector for NeverInjectSelector: %v (%v)", neverSelector, err)
} else if !selector.Empty() && selector.Matches(labels.Set(metadata.Labels)) {
log.Debugf("Explicitly disabling injection for pod %s/%s due to pod labels matching NeverInjectSelector config map entry.",
metadata.Namespace, potentialPodName(metadata))
inject = false
useDefault = false
break
}
}
}
// If there's no annotation nor a NeverInjectSelector, check the AlwaysInject one
if useDefault {
for _, alwaysSelector := range config.AlwaysInjectSelector {
selector, err := metav1.LabelSelectorAsSelector(&alwaysSelector)
if err != nil {
log.Warnf("Invalid selector for AlwaysInjectSelector: %v (%v)", alwaysSelector, err)
} else if !selector.Empty() && selector.Matches(labels.Set(metadata.Labels)) {
log.Debugf("Explicitly enabling injection for pod %s/%s due to pod labels matching AlwaysInjectSelector config map entry.",
metadata.Namespace, potentialPodName(metadata))
inject = true
useDefault = false
break
}
}
}
var required bool
switch config.Policy {
default: // InjectionPolicyOff
log.Errorf("Illegal value for autoInject:%s, must be one of [%s,%s]. Auto injection disabled!",
config.Policy, InjectionPolicyDisabled, InjectionPolicyEnabled)
required = false
case InjectionPolicyDisabled:
if useDefault {
required = false
} else {
required = inject
}
case InjectionPolicyEnabled:
if useDefault {
required = true
} else {
required = inject
}
}
if log.DebugEnabled() {
// Build a log message for the annotations.
annotationStr := ""
for name := range AnnotationValidation {
value, ok := annos[name]
if !ok {
value = "(unset)"
}
annotationStr += fmt.Sprintf("%s:%s ", name, value)
}
log.Debugf("Sidecar injection policy for %v/%v: namespacePolicy:%v useDefault:%v inject:%v required:%v %s",
metadata.Namespace,
potentialPodName(metadata),
config.Policy,
useDefault,
inject,
required,
annotationStr)
}
return required
}
// ProxyImage constructs image url in a backwards compatible way.
// values based name => {{ .Values.global.hub }}/{{ .Values.global.proxy.image }}:{{ .Values.global.tag }}
func ProxyImage(values *opconfig.Values, image *proxyConfig.ProxyImage, annotations map[string]string) string {
imageName := "proxyv2"
global := values.GetGlobal()
tag := ""
if global.GetTag() != nil { // Tag is an interface but we need the string form.
tag = fmt.Sprintf("%v", global.GetTag().AsInterface())
}
imageType := ""
if image != nil {
imageType = image.ImageType
}
if global.GetProxy() != nil && global.GetProxy().GetImage() != "" {
imageName = global.GetProxy().GetImage()
}
if it, ok := annotations[annotation.SidecarProxyImageType.Name]; ok {
imageType = it
}
return imageURL(global.GetHub(), imageName, tag, imageType)
}
// imageURL creates url from parts.
// imageType is appended if not empty
// if imageType is already present in the tag, then it is replaced.
// docker.io/istio/proxyv2:1.12-distroless
// gcr.io/gke-release/asm/proxyv2:1.11.2-asm.17-distroless
// docker.io/istio/proxyv2:1.12
func imageURL(hub, imageName, tag, imageType string) string {
return hub + "/" + imageName + ":" + updateImageTypeIfPresent(tag, imageType)
}
// KnownImageTypes are image types that istio pubishes.
var KnownImageTypes = []string{ImageTypeDistroless, ImageTypeDebug}
func updateImageTypeIfPresent(tag string, imageType string) string {
if imageType == "" {
return tag
}
for _, i := range KnownImageTypes {
if strings.HasSuffix(tag, "-"+i) {
tag = tag[:len(tag)-(len(i)+1)]
break
}
}
if imageType == ImageTypeDefault {
return tag
}
return tag + "-" + imageType
}
// RunTemplate renders the sidecar template
// Returns the raw string template, as well as the parse pod form
func RunTemplate(params InjectionParameters) (mergedPod *corev1.Pod, templatePod *corev1.Pod, err error) {
metadata := ¶ms.pod.ObjectMeta
meshConfig := params.meshConfig
if err := validateAnnotations(metadata.GetAnnotations()); err != nil {
log.Errorf("Injection failed due to invalid annotations: %v", err)
return nil, nil, err
}
cluster := params.valuesConfig.asStruct.GetGlobal().GetMultiCluster().GetClusterName()
// TODO allow overriding the values.global network in injection with the system namespace label
network := params.valuesConfig.asStruct.GetGlobal().GetNetwork()
// params may be set from webhook URL, take priority over values yaml
if params.proxyEnvs["ISTIO_META_CLUSTER_ID"] != "" {
cluster = params.proxyEnvs["ISTIO_META_CLUSTER_ID"]
}
if params.proxyEnvs["ISTIO_META_NETWORK"] != "" {
network = params.proxyEnvs["ISTIO_META_NETWORK"]
}
// explicit label takes highest precedence
if n, ok := metadata.Labels[label.TopologyNetwork.Name]; ok {
network = n
}
// use network in values for template, and proxy env variables
if cluster != "" {
params.proxyEnvs["ISTIO_META_CLUSTER_ID"] = cluster
}
if network != "" {
params.proxyEnvs["ISTIO_META_NETWORK"] = network
}
strippedPod, err := reinsertOverrides(stripPod(params))
if err != nil {
return nil, nil, err
}
proxyUID, proxyGID := GetProxyIDs(params.namespace)
data := SidecarTemplateData{
TypeMeta: params.typeMeta,
DeploymentMeta: params.deployMeta,
ObjectMeta: strippedPod.ObjectMeta,
Spec: strippedPod.Spec,
ProxyConfig: params.proxyConfig,
MeshConfig: meshConfig,
Values: params.valuesConfig.asMap,
Revision: params.revision,
ProxyImage: ProxyImage(params.valuesConfig.asStruct, params.proxyConfig.Image, strippedPod.Annotations),
ProxyUID: proxyUID,
ProxyGID: proxyGID,
}
mergedPod = params.pod
templatePod = &corev1.Pod{}
for _, templateName := range selectTemplates(params) {
parsedTemplate, f := params.templates[templateName]
if !f {
return nil, nil, fmt.Errorf("requested template %q not found; have %v",
templateName, strings.Join(knownTemplates(params.templates), ", "))
}
bbuf, err := runTemplate(parsedTemplate, data)
if err != nil {
return nil, nil, err
}
templatePod, err = applyOverlayYAML(templatePod, bbuf.Bytes())
if err != nil {
return nil, nil, fmt.Errorf("failed applying injection overlay: %v", err)
}
// This is a bit of a weird hack. With NativeSidecars, the container will be under initContainers in the template pod.
// But we may have injection customizations (https://istio.io/latest/docs/setup/additional-setup/sidecar-injection/#customizing-injection);
// these will be in the `containers` field.
// So if we see the proxy container in `containers` in the original pod, and in `initContainers` in the template pod,
// move the container.
if features.EnableNativeSidecars.Get() &&
FindContainer(ProxyContainerName, templatePod.Spec.InitContainers) != nil &&
FindContainer(ProxyContainerName, mergedPod.Spec.Containers) != nil {
mergedPod = mergedPod.DeepCopy()
mergedPod.Spec.Containers, mergedPod.Spec.InitContainers = moveContainer(mergedPod.Spec.Containers, mergedPod.Spec.InitContainers, ProxyContainerName)
}
mergedPod, err = applyOverlayYAML(mergedPod, bbuf.Bytes())
if err != nil {
return nil, nil, fmt.Errorf("failed parsing generated injected YAML (check Istio sidecar injector configuration): %v", err)
}
}
return mergedPod, templatePod, nil
}
func knownTemplates(t Templates) []string {
keys := make([]string, 0, len(t))
for k := range t {
keys = append(keys, k)
}
return keys
}
func selectTemplates(params InjectionParameters) []string {
if a, f := params.pod.Annotations[annotation.InjectTemplates.Name]; f {
names := []string{}
for _, tmplName := range strings.Split(a, ",") {
name := strings.TrimSpace(tmplName)
names = append(names, name)
}
return resolveAliases(params, names)
}
return resolveAliases(params, params.defaultTemplate)
}
func resolveAliases(params InjectionParameters, names []string) []string {
ret := []string{}
for _, name := range names {
if al, f := params.aliases[name]; f {
ret = append(ret, al...)
} else {
ret = append(ret, name)
}
}
return ret
}
func stripPod(req InjectionParameters) *corev1.Pod {
pod := req.pod.DeepCopy()
prevStatus := injectionStatus(pod)
if prevStatus == nil {
return req.pod
}
// We found a previous status annotation. Possibly we are re-injecting the pod
// To ensure idempotency, remove our injected containers first
for _, c := range prevStatus.Containers {
pod.Spec.Containers = modifyContainers(pod.Spec.Containers, c, Remove)
}
for _, c := range prevStatus.InitContainers {
pod.Spec.InitContainers = modifyContainers(pod.Spec.InitContainers, c, Remove)
}
targetPort := strconv.Itoa(int(req.meshConfig.GetDefaultConfig().GetStatusPort()))
if cur, f := getPrometheusPort(pod); f {
// We have already set the port, assume user is controlling this or, more likely, re-injected
// the pod.
if cur == targetPort {
clearPrometheusAnnotations(pod)
}
}
delete(pod.Annotations, annotation.SidecarStatus.Name)
return pod
}
func injectionStatus(pod *corev1.Pod) *SidecarInjectionStatus {
var statusBytes []byte
if pod.ObjectMeta.Annotations != nil {
if value, ok := pod.ObjectMeta.Annotations[annotation.SidecarStatus.Name]; ok {
statusBytes = []byte(value)
}
}
if statusBytes == nil {
return nil
}
// default case when injected pod has explicit status
var iStatus SidecarInjectionStatus
if err := json.Unmarshal(statusBytes, &iStatus); err != nil {
return nil
}
return &iStatus
}
func parseDryTemplate(tmplStr string, funcMap map[string]any) (*template.Template, error) {
temp := template.New("inject")
t, err := temp.Funcs(sprig.TxtFuncMap()).Funcs(funcMap).Parse(tmplStr)
if err != nil {
log.Infof("Failed to parse template: %v %v\n", err, tmplStr)
return nil, err
}
return t, nil
}
func runTemplate(tmpl *template.Template, data SidecarTemplateData) (bytes.Buffer, error) {
var res bytes.Buffer
if err := tmpl.Execute(&res, &data); err != nil {
log.Errorf("Invalid template: %v", err)
return bytes.Buffer{}, err
}
return res, nil
}
// IntoResourceFile injects the istio proxy into the specified
// kubernetes YAML file.
// nolint: lll
func IntoResourceFile(injector Injector, sidecarTemplate Templates,
valuesConfig ValuesConfig, revision string, meshconfig *meshconfig.MeshConfig, in io.Reader, out io.Writer, warningHandler func(string),
) error {
reader := yamlDecoder.NewYAMLReader(bufio.NewReaderSize(in, 4096))
for {
raw, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
obj, err := FromRawToObject(raw)
if err != nil && !runtime.IsNotRegisteredError(err) {
return err
}
var updated []byte
if err == nil {
outObject, err := IntoObject(injector, sidecarTemplate, valuesConfig, revision, meshconfig, obj, warningHandler) // nolint: vetshadow
if err != nil {
return err
}
if updated, err = yaml.Marshal(outObject); err != nil {
return err
}
} else {
updated = raw // unchanged
}
if _, err = out.Write(updated); err != nil {
return err
}
if _, err = fmt.Fprint(out, "---\n"); err != nil {
return err
}
}
return nil
}
// FromRawToObject is used to convert from raw to the runtime object
func FromRawToObject(raw []byte) (runtime.Object, error) {
var typeMeta metav1.TypeMeta
if err := yaml.Unmarshal(raw, &typeMeta); err != nil {
return nil, err
}
gvk := schema.FromAPIVersionAndKind(typeMeta.APIVersion, typeMeta.Kind)
obj, err := injectScheme.New(gvk)
if err != nil {
return nil, err
}
if err = yaml.Unmarshal(raw, obj); err != nil {
return nil, err
}
return obj, nil
}
// IntoObject convert the incoming resources into Injected resources
// nolint: lll
func IntoObject(injector Injector, sidecarTemplate Templates, valuesConfig ValuesConfig,
revision string, meshconfig *meshconfig.MeshConfig, in runtime.Object, warningHandler func(string),
) (any, error) {
out := in.DeepCopyObject()
var deploymentMetadata metav1.ObjectMeta
var metadata *metav1.ObjectMeta
var podSpec *corev1.PodSpec
var typeMeta metav1.TypeMeta
// Handle Lists
if list, ok := out.(*corev1.List); ok {
result := list
for i, item := range list.Items {
obj, err := FromRawToObject(item.Raw)
if runtime.IsNotRegisteredError(err) {
continue
}
if err != nil {
return nil, err
}
r, err := IntoObject(injector, sidecarTemplate, valuesConfig, revision, meshconfig, obj, warningHandler) // nolint: vetshadow
if err != nil {
return nil, err
}
re := runtime.RawExtension{}
re.Object = r.(runtime.Object)
result.Items[i] = re
}
return result, nil
}
// CronJobs have JobTemplates in them, instead of Templates, so we
// special case them.
switch v := out.(type) {
case *batch.CronJob:
job := v
typeMeta = job.TypeMeta
metadata = &job.Spec.JobTemplate.ObjectMeta
deploymentMetadata = job.ObjectMeta
podSpec = &job.Spec.JobTemplate.Spec.Template.Spec
case *corev1.Pod:
pod := v
typeMeta = pod.TypeMeta
metadata = &pod.ObjectMeta
deploymentMetadata = pod.ObjectMeta
podSpec = &pod.Spec
case *appsv1.Deployment: // Added to be explicit about the most expected case
deploy := v
typeMeta = deploy.TypeMeta
deploymentMetadata = deploy.ObjectMeta
metadata = &deploy.Spec.Template.ObjectMeta
podSpec = &deploy.Spec.Template.Spec
default:
// `in` is a pointer to an Object. Dereference it.
outValue := reflect.ValueOf(out).Elem()
typeMeta = outValue.FieldByName("TypeMeta").Interface().(metav1.TypeMeta)
deploymentMetadata = outValue.FieldByName("ObjectMeta").Interface().(metav1.ObjectMeta)
templateValue := outValue.FieldByName("Spec").FieldByName("Template")
// `Template` is defined as a pointer in some older API
// definitions, e.g. ReplicationController
if templateValue.Kind() == reflect.Ptr {
if templateValue.IsNil() {
return out, fmt.Errorf("spec.template is required value")
}
templateValue = templateValue.Elem()
}
metadata = templateValue.FieldByName("ObjectMeta").Addr().Interface().(*metav1.ObjectMeta)
podSpec = templateValue.FieldByName("Spec").Addr().Interface().(*corev1.PodSpec)
}
name := metadata.Name
if name == "" {
name = deploymentMetadata.Name
}
namespace := metadata.Namespace
if namespace == "" {
namespace = deploymentMetadata.Namespace
}
var fullName string
if deploymentMetadata.Namespace != "" {
fullName = fmt.Sprintf("%s/%s", deploymentMetadata.Namespace, name)
} else {
fullName = name
}
kind := typeMeta.Kind
// Skip injection when host networking is enabled. The problem is
// that the iptable changes are assumed to be within the pod when,
// in fact, they are changing the routing at the host level. This
// often results in routing failures within a node which can
// affect the network provider within the cluster causing
// additional pod failures.
if podSpec.HostNetwork {
warningStr := fmt.Sprintf("===> Skipping injection because %q has host networking enabled\n",
fullName)
if kind != "" {
warningStr = fmt.Sprintf("===> Skipping injection because %s %q has host networking enabled\n",
kind, fullName)
}
warningHandler(warningStr)
return out, nil
}
pod := &corev1.Pod{
ObjectMeta: *metadata,
Spec: *podSpec,
}
var patchBytes []byte
var err error
if injector != nil {
patchBytes, err = injector.Inject(pod, namespace)
}
if err != nil {
return nil, err
}
// TODO(Monkeyanator) istioctl injection still applies just the pod annotation since we don't have
// the ProxyConfig CRs here.
if pca, f := metadata.GetAnnotations()[annotation.ProxyConfig.Name]; f {
var merr error
meshconfig, merr = mesh.ApplyProxyConfig(pca, meshconfig)
if merr != nil {
return nil, merr
}
}
if patchBytes == nil {
if !injectRequired(IgnoredNamespaces.UnsortedList(), &Config{Policy: InjectionPolicyEnabled}, &pod.Spec, pod.ObjectMeta) {
warningStr := fmt.Sprintf("===> Skipping injection because %q has sidecar injection disabled\n", fullName)
if kind != "" {
warningStr = fmt.Sprintf("===> Skipping injection because %s %q has sidecar injection disabled\n",
kind, fullName)
}
warningHandler(warningStr)
return out, nil
}
params := InjectionParameters{
pod: pod,
deployMeta: deploymentMetadata,
typeMeta: typeMeta,
// Todo replace with some template resolver abstraction
templates: sidecarTemplate,
defaultTemplate: []string{SidecarTemplateName},
meshConfig: meshconfig,
proxyConfig: meshconfig.GetDefaultConfig(),
valuesConfig: valuesConfig,
revision: revision,
proxyEnvs: map[string]string{},
injectedAnnotations: nil,
}
patchBytes, err = injectPod(params)
}
if err != nil {
return nil, err
}
patched, err := applyJSONPatchToPod(pod, patchBytes)
if err != nil {
return nil, err
}
patchedObject, _, err := jsonSerializer.Decode(patched, nil, &corev1.Pod{})
if err != nil {
return nil, err
}
patchedPod := patchedObject.(*corev1.Pod)
*metadata = patchedPod.ObjectMeta
*podSpec = patchedPod.Spec
return out, nil
}
func applyJSONPatchToPod(input *corev1.Pod, patch []byte) ([]byte, error) {
objJS, err := runtime.Encode(jsonSerializer, input)
if err != nil {
return nil, err
}
p, err := jsonpatch.DecodePatch(patch)
if err != nil {
return nil, err
}
patchedJSON, err := p.Apply(objJS)
if err != nil {
return nil, err
}
return patchedJSON, nil
}
// SidecarInjectionStatus contains basic information about the
// injected sidecar. This includes the names of added containers and
// volumes.
type SidecarInjectionStatus struct {
InitContainers []string `json:"initContainers"`
Containers []string `json:"containers"`
Volumes []string `json:"volumes"`
ImagePullSecrets []string `json:"imagePullSecrets"`
Revision string `json:"revision"`
}
func potentialPodName(metadata metav1.ObjectMeta) string {
if metadata.Name != "" {
return metadata.Name
}
if metadata.GenerateName != "" {
return metadata.GenerateName + "***** (actual name not yet known)"
}
return ""
}
// overwriteClusterInfo updates cluster name and network from url path
// This is needed when webconfig config runs on a different cluster than webhook
func overwriteClusterInfo(pod *corev1.Pod, params InjectionParameters) {
c := FindSidecar(pod)
if c == nil {
return
}
if len(params.proxyEnvs) > 0 {
log.Debugf("Updating cluster envs based on inject url: %s\n", params.proxyEnvs)
updateClusterEnvs(c, params.proxyEnvs)
}
}
func updateClusterEnvs(container *corev1.Container, newKVs map[string]string) {
envVars := make([]corev1.EnvVar, 0)
for _, env := range container.Env {
if _, found := newKVs[env.Name]; !found {
envVars = append(envVars, env)
}
}
keys := make([]string, 0, len(newKVs))
for key := range newKVs {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
val := newKVs[key]
envVars = append(envVars, corev1.EnvVar{Name: key, Value: val, ValueFrom: nil})
}
container.Env = envVars
}
// GetProxyIDs returns the UID and GID to be used in the RunAsUser and RunAsGroup fields in the template
// Inspects the namespace metadata for hints and fallbacks to the usual value of 1337.
func GetProxyIDs(namespace *corev1.Namespace) (uid int64, gid int64) {
uid = constants.DefaultProxyUIDInt
gid = constants.DefaultProxyUIDInt
if namespace == nil {
return
}
// Check for OpenShift specifics and returns the max number in the range specified in the namespace annotation
if _, uidMax, err := getPreallocatedUIDRange(namespace); err == nil {
uid = *uidMax
}
if groups, err := getPreallocatedSupplementalGroups(namespace); err == nil && len(groups) > 0 {
gid = groups[0].Max
}
return
}