-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
workload.go
693 lines (639 loc) · 25.5 KB
/
workload.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
// 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 workload
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/spf13/cobra"
authenticationv1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/yaml"
"istio.io/api/annotation"
"istio.io/api/label"
meshconfig "istio.io/api/mesh/v1alpha1"
networkingv1alpha3 "istio.io/api/networking/v1alpha3"
clientv1alpha3 "istio.io/client-go/pkg/apis/networking/v1alpha3"
"istio.io/istio/istioctl/pkg/cli"
"istio.io/istio/istioctl/pkg/clioptions"
"istio.io/istio/istioctl/pkg/completion"
istioctlutil "istio.io/istio/istioctl/pkg/util"
"istio.io/istio/operator/pkg/tpath"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pilot/pkg/serviceregistry/kube/controller"
"istio.io/istio/pkg/config/constants"
"istio.io/istio/pkg/config/schema/gvk"
"istio.io/istio/pkg/config/validation/agent"
"istio.io/istio/pkg/kube"
"istio.io/istio/pkg/kube/labels"
"istio.io/istio/pkg/log"
netutil "istio.io/istio/pkg/util/net"
"istio.io/istio/pkg/util/protomarshal"
"istio.io/istio/pkg/util/shellescape"
)
var (
// TODO refactor away from package vars and add more UTs
tokenDuration int64
name string
serviceAccount string
filename string
outputDir string
clusterID string
ingressIP string
internalIP string
externalIP string
ingressSvc string
autoRegister bool
dnsCapture bool
ports []string
resourceLabels []string
annotations []string
namespace string
)
const (
istioEastWestGatewayServiceName = "istio-eastwestgateway"
filePerms = os.FileMode(0o744)
)
func Cmd(ctx cli.Context) *cobra.Command {
namespace = ctx.Namespace()
workloadCmd := &cobra.Command{
Use: "workload",
Short: "Commands to assist in configuring and deploying workloads running on VMs and other non-Kubernetes environments",
Example: ` # workload group yaml generation
istioctl x workload group create
# workload entry configuration generation
istioctl x workload entry configure`,
}
workloadCmd.AddCommand(groupCommand(ctx))
workloadCmd.AddCommand(entryCommand(ctx))
return workloadCmd
}
func groupCommand(ctx cli.Context) *cobra.Command {
groupCmd := &cobra.Command{
Use: "group",
Short: "Commands dealing with WorkloadGroup resources",
Example: " istioctl x workload group create --name foo --namespace bar --labels app=foobar",
}
groupCmd.AddCommand(createCommand(ctx))
return groupCmd
}
func entryCommand(ctx cli.Context) *cobra.Command {
entryCmd := &cobra.Command{
Use: "entry",
Short: "Commands dealing with WorkloadEntry resources",
Example: " istioctl x workload entry configure -f workloadgroup.yaml -o outputDir",
}
entryCmd.AddCommand(configureCommand(ctx))
return entryCmd
}
func createCommand(ctx cli.Context) *cobra.Command {
createCmd := &cobra.Command{
Use: "create",
Short: "Creates a WorkloadGroup resource that provides a template for associated WorkloadEntries",
Long: `Creates a WorkloadGroup resource that provides a template for associated WorkloadEntries.
The default output is serialized YAML, which can be piped into 'kubectl apply -f -' to send the artifact to the API Server.`,
Example: " istioctl x workload group create --name foo --namespace bar --labels app=foo,bar=baz " +
"--ports grpc=3550,http=8080 --annotations annotation=foobar --serviceAccount sa",
Args: func(cmd *cobra.Command, args []string) error {
if name == "" {
return fmt.Errorf("expecting a workload name")
}
if namespace == "" {
return fmt.Errorf("expecting a workload namespace")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
u := &unstructured.Unstructured{
Object: map[string]any{
"apiVersion": gvk.WorkloadGroup.GroupVersion(),
"kind": gvk.WorkloadGroup.Kind,
"metadata": map[string]any{
"name": name,
"namespace": namespace,
},
},
}
spec := &networkingv1alpha3.WorkloadGroup{
Metadata: &networkingv1alpha3.WorkloadGroup_ObjectMeta{
Labels: convertToStringMap(resourceLabels),
Annotations: convertToStringMap(annotations),
},
Template: &networkingv1alpha3.WorkloadEntry{
Ports: convertToUnsignedInt32Map(ports),
ServiceAccount: serviceAccount,
},
}
wgYAML, err := generateWorkloadGroupYAML(u, spec)
if err != nil {
return err
}
_, err = cmd.OutOrStdout().Write(wgYAML)
return err
},
}
createCmd.PersistentFlags().StringVar(&name, "name", "", "The name of the workload group")
createCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "The namespace that the workload instances will belong to")
createCmd.PersistentFlags().StringSliceVarP(&resourceLabels, "labels", "l", nil, "The labels to apply to the workload instances; e.g. -l env=prod,vers=2")
createCmd.PersistentFlags().StringSliceVarP(&annotations, "annotations", "a", nil, "The annotations to apply to the workload instances")
createCmd.PersistentFlags().StringSliceVarP(&ports, "ports", "p", nil, "The incoming ports exposed by the workload instance")
createCmd.PersistentFlags().StringVarP(&serviceAccount, "serviceAccount", "s", "default", "The service identity to associate with the workload instances")
_ = createCmd.RegisterFlagCompletionFunc("serviceAccount", func(
cmd *cobra.Command, args []string, toComplete string,
) ([]string, cobra.ShellCompDirective) {
return completion.ValidServiceAccountArgs(cmd, ctx, args, toComplete)
})
return createCmd
}
func generateWorkloadGroupYAML(u *unstructured.Unstructured, spec *networkingv1alpha3.WorkloadGroup) ([]byte, error) {
iSpec, err := unstructureIstioType(spec)
if err != nil {
return nil, err
}
u.Object["spec"] = iSpec
wgYAML, err := yaml.Marshal(u.Object)
if err != nil {
return nil, err
}
return wgYAML, nil
}
func configureCommand(ctx cli.Context) *cobra.Command {
var opts clioptions.ControlPlaneOptions
configureCmd := &cobra.Command{
Use: "configure",
Short: "Generates all the required configuration files for a workload instance running on a VM or non-Kubernetes environment",
Long: `Generates all the required configuration files for workload instance on a VM or non-Kubernetes environment from a WorkloadGroup artifact.
This includes a MeshConfig resource, the cluster.env file, and necessary certificates and security tokens.
Configure requires either the WorkloadGroup artifact path or its location on the API server.`,
Example: ` # configure example using a local WorkloadGroup artifact
istioctl x workload entry configure -f workloadgroup.yaml -o config
# configure example using the API server
istioctl x workload entry configure --name foo --namespace bar -o config`,
Args: func(cmd *cobra.Command, args []string) error {
if filename == "" && (name == "" || namespace == "") {
return fmt.Errorf("expecting a WorkloadGroup artifact file or the name and namespace of an existing WorkloadGroup")
}
if outputDir == "" {
return fmt.Errorf("expecting an output directory")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
kubeClient, err := ctx.CLIClientWithRevision(opts.Revision)
if err != nil {
return err
}
wg := &clientv1alpha3.WorkloadGroup{}
if filename != "" {
if err := readWorkloadGroup(filename, wg); err != nil {
return err
}
} else {
wg, err = kubeClient.Istio().NetworkingV1alpha3().WorkloadGroups(namespace).Get(context.Background(), name, metav1.GetOptions{})
// errors if the requested workload group does not exist in the given namespace
if err != nil {
return fmt.Errorf("workloadgroup %s not found in namespace %s: %v", name, namespace, err)
}
}
// extract the cluster ID from the injector config (.Values.global.multiCluster.clusterName)
if !validateFlagIsSetManuallyOrNot(cmd, "clusterID") {
// extract the cluster ID from the injector config if it is not set by user
clusterName, err := extractClusterIDFromInjectionConfig(kubeClient, ctx.IstioNamespace())
if err != nil {
return fmt.Errorf("failed to automatically determine the --clusterID: %v", err)
}
if clusterName != "" {
clusterID = clusterName
}
}
if err = createConfig(kubeClient, wg, ctx.IstioNamespace(), clusterID, ingressIP, internalIP, externalIP, outputDir, cmd.OutOrStderr()); err != nil {
return err
}
fmt.Printf("Configuration generation into directory %s was successful\n", outputDir)
return nil
},
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(internalIP) > 0 && len(externalIP) > 0 {
return fmt.Errorf("the flags --internalIP and --externalIP are mutually exclusive")
}
return nil
},
}
configureCmd.PersistentFlags().StringVarP(&filename, "file", "f", "", "filename of the WorkloadGroup artifact. Leave this field empty if using the API server")
configureCmd.PersistentFlags().StringVar(&name, "name", "", "The name of the workload group")
configureCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "The namespace that the workload instances belong to")
configureCmd.PersistentFlags().StringVarP(&outputDir, "output", "o", "", "Output directory for generated files")
configureCmd.PersistentFlags().StringVar(&clusterID, "clusterID", "", "The ID used to identify the cluster")
configureCmd.PersistentFlags().Int64Var(&tokenDuration, "tokenDuration", 3600, "The token duration in seconds (default: 1 hour)")
configureCmd.PersistentFlags().StringVar(&ingressSvc, "ingressService", istioEastWestGatewayServiceName, "Name of the Service to be"+
" used as the ingress gateway, in the format <service>.<namespace>. If no namespace is provided, the default "+ctx.IstioNamespace()+
" namespace will be used.")
configureCmd.PersistentFlags().StringVar(&ingressIP, "ingressIP", "", "IP address of the ingress gateway")
configureCmd.PersistentFlags().BoolVar(&autoRegister, "autoregister", false, "Creates a WorkloadEntry upon connection to istiod (if enabled in pilot).")
configureCmd.PersistentFlags().BoolVar(&dnsCapture, "capture-dns", true, "Enables the capture of outgoing DNS packets on port 53, redirecting to istio-agent")
configureCmd.PersistentFlags().StringVar(&internalIP, "internalIP", "", "Internal IP address of the workload")
configureCmd.PersistentFlags().StringVar(&externalIP, "externalIP", "", "External IP address of the workload")
opts.AttachControlPlaneFlags(configureCmd)
return configureCmd
}
// Reads a WorkloadGroup yaml. Additionally populates default values if unset
// TODO: add WorkloadGroup validation in pkg/config/validation
func readWorkloadGroup(filename string, wg *clientv1alpha3.WorkloadGroup) error {
f, err := os.ReadFile(filename)
if err != nil {
return err
}
if err = yaml.Unmarshal(f, wg); err != nil {
return err
}
// fill empty structs
if wg.Spec.Metadata == nil {
wg.Spec.Metadata = &networkingv1alpha3.WorkloadGroup_ObjectMeta{}
}
if wg.Spec.Template == nil {
wg.Spec.Template = &networkingv1alpha3.WorkloadEntry{}
}
// default service account for an empty field is "default"
if wg.Spec.Template.ServiceAccount == "" {
wg.Spec.Template.ServiceAccount = "default"
}
return nil
}
// Creates all the relevant config for the given workload group and cluster
func createConfig(kubeClient kube.CLIClient, wg *clientv1alpha3.WorkloadGroup, istioNamespace, clusterID, ingressIP, internalIP,
externalIP string, outputDir string, out io.Writer,
) error {
if err := os.MkdirAll(outputDir, filePerms); err != nil {
return err
}
var (
err error
proxyConfig *meshconfig.ProxyConfig
)
revision := kubeClient.Revision()
if proxyConfig, err = createMeshConfig(kubeClient, wg, istioNamespace, clusterID, outputDir, revision); err != nil {
return err
}
if err := createClusterEnv(wg, proxyConfig, istioNamespace, revision, internalIP, externalIP, outputDir); err != nil {
return err
}
if err := createCertsTokens(kubeClient, wg, outputDir, out); err != nil {
return err
}
if err := createHosts(kubeClient, istioNamespace, ingressIP, outputDir, revision); err != nil {
return err
}
return nil
}
// Write cluster.env into the given directory
func createClusterEnv(wg *clientv1alpha3.WorkloadGroup, config *meshconfig.ProxyConfig, istioNamespace, revision, internalIP, externalIP, dir string) error {
we := wg.Spec.Template
ports := []string{}
for _, v := range we.Ports {
ports = append(ports, fmt.Sprint(v))
}
// respect the inbound port annotation and capture all traffic if no inbound ports are set
portBehavior := "*"
if len(ports) > 0 {
portBehavior = strings.Join(ports, ",")
}
// 22: ssh is extremely common for VMs, and we do not want to make VM inaccessible if there is an issue
// 15090: prometheus
// 15021/15020: agent
excludePorts := "22,15090,15021"
if config.StatusPort != 15090 && config.StatusPort != 15021 {
if config.StatusPort != 0 {
// Explicit status port set, use that
excludePorts += fmt.Sprintf(",%d", config.StatusPort)
} else {
// use default status port
excludePorts += ",15020"
}
}
// default attributes and service name, namespace, ports, service account, service CIDR
overrides := map[string]string{
"ISTIO_INBOUND_PORTS": portBehavior,
"ISTIO_NAMESPACE": wg.Namespace,
"ISTIO_SERVICE": fmt.Sprintf("%s.%s", wg.Name, wg.Namespace),
"ISTIO_SERVICE_CIDR": "*",
"ISTIO_LOCAL_EXCLUDE_PORTS": excludePorts,
"SERVICE_ACCOUNT": we.ServiceAccount,
}
if isRevisioned(revision) {
overrides["CA_ADDR"] = IstiodAddr(istioNamespace, revision)
}
if len(internalIP) > 0 {
overrides["ISTIO_SVC_IP"] = internalIP
} else if len(externalIP) > 0 {
overrides["ISTIO_SVC_IP"] = externalIP
overrides["REWRITE_PROBE_LEGACY_LOCALHOST_DESTINATION"] = "true"
}
// clusterEnv will use proxyMetadata from the proxyConfig + overrides specific to the WorkloadGroup and cmd args
// this is similar to the way the injector sets all values proxyConfig.proxyMetadata to the Pod's env
clusterEnv := map[string]string{}
for _, metaMap := range []map[string]string{config.ProxyMetadata, overrides} {
for k, v := range metaMap {
clusterEnv[k] = v
}
}
return os.WriteFile(filepath.Join(dir, "cluster.env"), []byte(mapToString(clusterEnv)), filePerms)
}
// Get and store the needed certificate and token. The certificate comes from the CA root cert, and
// the token is generated by kubectl under the workload group's namespace and service account
// TODO: Make the following accurate when using the Kubernetes certificate signer
func createCertsTokens(kubeClient kube.CLIClient, wg *clientv1alpha3.WorkloadGroup, dir string, out io.Writer) error {
rootCert, err := kubeClient.Kube().CoreV1().ConfigMaps(wg.Namespace).Get(context.Background(), controller.CACertNamespaceConfigMap, metav1.GetOptions{})
// errors if the requested configmap does not exist in the given namespace
if err != nil {
return fmt.Errorf("configmap %s was not found in namespace %s: %v", controller.CACertNamespaceConfigMap, wg.Namespace, err)
}
if err = os.WriteFile(filepath.Join(dir, "root-cert.pem"), []byte(rootCert.Data[constants.CACertNamespaceConfigMapDataName]), filePerms); err != nil {
return err
}
serviceAccount := wg.Spec.Template.ServiceAccount
tokenPath := filepath.Join(dir, "istio-token")
token := &authenticationv1.TokenRequest{
// ObjectMeta isn't required in real k8s, but needed for tests
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccount,
Namespace: wg.Namespace,
},
Spec: authenticationv1.TokenRequestSpec{
Audiences: []string{"istio-ca"},
ExpirationSeconds: &tokenDuration,
},
}
tokenReq, err := kubeClient.Kube().CoreV1().ServiceAccounts(wg.Namespace).CreateToken(context.Background(), serviceAccount, token, metav1.CreateOptions{})
// errors if the token could not be created with the given service account in the given namespace
if err != nil {
return fmt.Errorf("could not create a token under service account %s in namespace %s: %v", serviceAccount, wg.Namespace, err)
}
if err := os.WriteFile(tokenPath, []byte(tokenReq.Status.Token), filePerms); err != nil {
return err
}
fmt.Fprintf(out, "Warning: a security token for namespace %q and service account %q has been generated and "+
"stored at %q\n", wg.Namespace, serviceAccount, tokenPath)
return nil
}
func createMeshConfig(kubeClient kube.CLIClient, wg *clientv1alpha3.WorkloadGroup, istioNamespace, clusterID, dir,
revision string,
) (*meshconfig.ProxyConfig, error) {
istioCM := "istio"
// Case with multiple control planes
if isRevisioned(revision) {
istioCM = fmt.Sprintf("%s-%s", istioCM, revision)
}
istio, err := kubeClient.Kube().CoreV1().ConfigMaps(istioNamespace).Get(context.Background(), istioCM, metav1.GetOptions{})
// errors if the requested configmap does not exist in the given namespace
if err != nil {
return nil, fmt.Errorf("configmap %s was not found in namespace %s: %v", istioCM, istioNamespace, err)
}
// fill some fields before applying the yaml to prevent errors later
meshConfig := &meshconfig.MeshConfig{
DefaultConfig: &meshconfig.ProxyConfig{
ProxyMetadata: map[string]string{},
},
}
if err := protomarshal.ApplyYAML(istio.Data[istioctlutil.ConfigMapKey], meshConfig); err != nil {
return nil, err
}
if isRevisioned(revision) && meshConfig.DefaultConfig.DiscoveryAddress == "" {
meshConfig.DefaultConfig.DiscoveryAddress = IstiodAddr(istioNamespace, revision)
}
// performing separate map-merge, apply seems to completely overwrite all metadata
proxyMetadata := meshConfig.DefaultConfig.ProxyMetadata
// support proxy.istio.io/config on the WorkloadGroup, in the WorkloadGroup spec
for _, annotations := range []map[string]string{wg.Annotations, wg.Spec.Metadata.Annotations} {
if pcYaml, ok := annotations[annotation.ProxyConfig.Name]; ok {
if err := protomarshal.ApplyYAML(pcYaml, meshConfig.DefaultConfig); err != nil {
return nil, err
}
for k, v := range meshConfig.DefaultConfig.ProxyMetadata {
proxyMetadata[k] = v
}
}
}
meshConfig.DefaultConfig.ProxyMetadata = proxyMetadata
lbls := map[string]string{}
for k, v := range wg.Spec.Metadata.Labels {
lbls[k] = v
}
// case where a user provided custom workload group has labels in the workload entry template field
we := wg.Spec.Template
if len(we.Labels) > 0 {
fmt.Printf("Labels should be set in the metadata. The following WorkloadEntry labels will override metadata labels: %s\n", we.Labels)
for k, v := range we.Labels {
lbls[k] = v
}
}
meshConfig.DefaultConfig.ReadinessProbe = wg.Spec.Probe
md := meshConfig.DefaultConfig.ProxyMetadata
if md == nil {
md = map[string]string{}
meshConfig.DefaultConfig.ProxyMetadata = md
}
md["CANONICAL_SERVICE"], md["CANONICAL_REVISION"] = labels.CanonicalService(lbls, wg.Name)
md["POD_NAMESPACE"] = wg.Namespace
md["SERVICE_ACCOUNT"] = we.ServiceAccount
md["TRUST_DOMAIN"] = meshConfig.TrustDomain
md["ISTIO_META_CLUSTER_ID"] = clusterID
md["ISTIO_META_MESH_ID"] = meshConfig.DefaultConfig.MeshId
md["ISTIO_META_NETWORK"] = we.Network
if portsStr := marshalWorkloadEntryPodPorts(we.Ports); portsStr != "" {
md["ISTIO_META_POD_PORTS"] = portsStr
}
md["ISTIO_META_WORKLOAD_NAME"] = wg.Name
lbls[label.ServiceCanonicalName.Name] = md["CANONICAL_SERVICE"]
lbls[label.ServiceCanonicalRevision.Name] = md["CANONICAL_REVISION"]
if labelsJSON, err := json.Marshal(lbls); err == nil {
md["ISTIO_METAJSON_LABELS"] = string(labelsJSON)
}
// TODO the defaults should be controlled by meshConfig/proxyConfig; if flags not given to the command proxyCOnfig takes precedence
if dnsCapture {
md["ISTIO_META_DNS_CAPTURE"] = strconv.FormatBool(dnsCapture)
}
if autoRegister {
md["ISTIO_META_AUTO_REGISTER_GROUP"] = wg.Name
}
proxyConfig, err := protomarshal.ToJSONMap(meshConfig.DefaultConfig)
if err != nil {
return nil, err
}
proxyYAML, err := yaml.Marshal(map[string]any{"defaultConfig": proxyConfig})
if err != nil {
return nil, err
}
return meshConfig.DefaultConfig, os.WriteFile(filepath.Join(dir, "mesh.yaml"), proxyYAML, filePerms)
}
func marshalWorkloadEntryPodPorts(p map[string]uint32) string {
var out []model.PodPort
for name, port := range p {
out = append(out, model.PodPort{Name: name, ContainerPort: int(port)})
}
if len(out) == 0 {
return ""
}
sort.Slice(out, func(i, j int) bool {
return out[i].Name < out[j].Name
})
str, err := json.Marshal(out)
if err != nil {
return ""
}
return string(str)
}
// Retrieves the external IP of the ingress-gateway for the hosts file additions
func createHosts(kubeClient kube.CLIClient, istioNamespace, ingressIP, dir string, revision string) error {
// try to infer the ingress IP if the provided one is invalid
if agent.ValidateIPAddress(ingressIP) != nil {
p := strings.Split(ingressSvc, ".")
ingressNs := istioNamespace
if len(p) == 2 {
ingressSvc = p[0]
ingressNs = p[1]
}
ingress, err := kubeClient.Kube().CoreV1().Services(ingressNs).Get(context.Background(), ingressSvc, metav1.GetOptions{})
if err == nil {
if ingress.Status.LoadBalancer.Ingress != nil && len(ingress.Status.LoadBalancer.Ingress) > 0 {
ingressIP = ingress.Status.LoadBalancer.Ingress[0].IP
} else if len(ingress.Spec.ExternalIPs) > 0 {
ingressIP = ingress.Spec.ExternalIPs[0]
}
// TODO: add case where the load balancer is a DNS name
}
}
var hosts string
if netutil.IsValidIPAddress(ingressIP) {
hosts = fmt.Sprintf("%s %s\n", ingressIP, IstiodHost(istioNamespace, revision))
} else {
log.Warnf("Could not auto-detect IP for %s/%s. Use --ingressIP to manually specify the Gateway address to reach istiod from the VM.",
IstiodHost(istioNamespace, revision), istioNamespace)
}
return os.WriteFile(filepath.Join(dir, "hosts"), []byte(hosts), filePerms)
}
func isRevisioned(revision string) bool {
return revision != "" && revision != "default"
}
func IstiodHost(ns string, revision string) string {
istiod := "istiod"
if isRevisioned(revision) {
istiod = fmt.Sprintf("%s-%s", istiod, revision)
}
return fmt.Sprintf("%s.%s.svc", istiod, ns)
}
func IstiodAddr(ns, revision string) string {
// TODO make port configurable
return fmt.Sprintf("%s:%d", IstiodHost(ns, revision), 15012)
}
// Returns a map with each k,v entry on a new line
func mapToString(m map[string]string) string {
lines := []string{}
for k, v := range m {
lines = append(lines, fmt.Sprintf("%s=%s", k, shellescape.Quote(v)))
}
sort.Strings(lines)
return strings.Join(lines, "\n") + "\n"
}
// extractClusterIDFromInjectionConfig can extract clusterID from injection configmap
func extractClusterIDFromInjectionConfig(kubeClient kube.CLIClient, istioNamespace string) (string, error) {
injectionConfigMap := "istio-sidecar-injector"
// Case with multiple control planes
revision := kubeClient.Revision()
if isRevisioned(revision) {
injectionConfigMap = fmt.Sprintf("%s-%s", injectionConfigMap, revision)
}
istioInjectionCM, err := kubeClient.Kube().CoreV1().ConfigMaps(istioNamespace).Get(context.Background(), injectionConfigMap, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("fetch injection template: %v", err)
}
var injectedCMValues map[string]any
if err := json.Unmarshal([]byte(istioInjectionCM.Data[istioctlutil.ValuesConfigMapKey]), &injectedCMValues); err != nil {
return "", err
}
v, f, err := tpath.GetFromStructPath(injectedCMValues, "global.multiCluster.clusterName")
if err != nil {
return "", err
}
vs, ok := v.(string)
if !f || !ok {
return "", fmt.Errorf("could not retrieve global.multiCluster.clusterName from injection config")
}
return vs, nil
}
// Because we are placing into an Unstructured, place as a map instead
// of structured Istio types. (The go-client can handle the structured data, but the
// fake go-client used for mocking cannot.)
func unstructureIstioType(spec any) (map[string]any, error) {
b, err := yaml.Marshal(spec)
if err != nil {
return nil, err
}
iSpec := map[string]any{}
err = yaml.Unmarshal(b, &iSpec)
if err != nil {
return nil, err
}
return iSpec, nil
}
func convertToUnsignedInt32Map(s []string) map[string]uint32 {
out := make(map[string]uint32, len(s))
for _, l := range s {
k, v := splitEqual(l)
u64, err := strconv.ParseUint(v, 10, 32)
if err != nil {
log.Errorf("failed to convert to uint32: %v", err)
}
out[k] = uint32(u64)
}
return out
}
func convertToStringMap(s []string) map[string]string {
out := make(map[string]string, len(s))
for _, l := range s {
k, v := splitEqual(l)
out[k] = v
}
return out
}
// splitEqual splits key=value string into key,value. if no = is found
// the whole string is the key and value is empty.
func splitEqual(str string) (string, string) {
idx := strings.Index(str, "=")
var k string
var v string
if idx >= 0 {
k = str[:idx]
v = str[idx+1:]
} else {
k = str
}
return k, v
}
// validateFlagIsSetManuallyOrNot can validate that a persistent flag is set manually or not by user for given command
func validateFlagIsSetManuallyOrNot(istioCmd *cobra.Command, flagName string) bool {
if istioCmd != nil {
allPersistentFlagSet := istioCmd.PersistentFlags()
if flagName != "" {
return allPersistentFlagSet.Changed(flagName)
}
}
return false
}