-
Notifications
You must be signed in to change notification settings - Fork 21
/
context.go
2128 lines (1870 loc) · 70.7 KB
/
context.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
// Copyright 2022 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package command
import (
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kerrors "k8s.io/apimachinery/pkg/util/errors"
clientauthv1 "k8s.io/client-go/pkg/apis/clientauthentication/v1"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/vmware-tanzu/tanzu-cli/pkg/common"
"github.com/vmware-tanzu/tanzu-plugin-runtime/component"
"github.com/vmware-tanzu/tanzu-plugin-runtime/config"
configtypes "github.com/vmware-tanzu/tanzu-plugin-runtime/config/types"
"github.com/vmware-tanzu/tanzu-plugin-runtime/log"
"github.com/vmware-tanzu/tanzu-plugin-runtime/plugin"
"github.com/vmware-tanzu/tanzu-cli/pkg/auth/csp"
tanzuauth "github.com/vmware-tanzu/tanzu-cli/pkg/auth/tanzu"
tkgauth "github.com/vmware-tanzu/tanzu-cli/pkg/auth/tkg"
kubecfg "github.com/vmware-tanzu/tanzu-cli/pkg/auth/utils/kubeconfig"
wcpauth "github.com/vmware-tanzu/tanzu-cli/pkg/auth/wcp"
"github.com/vmware-tanzu/tanzu-cli/pkg/cli"
"github.com/vmware-tanzu/tanzu-cli/pkg/constants"
"github.com/vmware-tanzu/tanzu-cli/pkg/discovery"
"github.com/vmware-tanzu/tanzu-cli/pkg/pluginmanager"
"github.com/vmware-tanzu/tanzu-cli/pkg/utils"
)
var (
stderrOnly, forceCSP, staging, onlyCurrent, skipTLSVerify, showAllColumns, shortCtx bool
ctxName, endpoint, apiToken, kubeConfig, kubeContext, getOutputFmt, endpointCACertPath string
projectStr, projectIDStr, spaceStr, clustergroupStr string
contextTypeStr string
)
const (
knownGlobalHost = "cloud.vmware.com"
defaultTanzuEndpoint = "https://api.tanzu.cloud.vmware.com"
isPinnipedEndpoint = "isPinnipedEndpoint"
tanzuMissionControlEndpoint = "tanzuMissionControlEndpoint"
contextNotExistsForContextType = "The provided context '%v' does not exist or is not active for the given context type '%v'"
noActiveContextExistsForContextType = "There is no active context for the given context type '%v'"
contextNotActiveOrNotExists = "The provided context '%v' is not active or does not exist"
contextForContextTypeSetInactive = "The context '%v' of type '%v' has been set as inactive"
deactivatingPlugin = "Deactivating plugin '%v:%v' for context '%v'"
invalidTargetErrorForContextCommands = "invalid target specified. Please specify a correct value for the `--target` flag from 'kubernetes[k8s]/mission-control[tmc]'"
invalidContextType = "invalid context type specified. Please specify a correct value for the `--type/-t` flag from 'kubernetes[k8s]/mission-control[tmc]/tanzu'"
)
// constants that define context creation types
const (
contextMissionControl ContextCreationType = "Mission Control"
contextK8SClusterEndpoint ContextCreationType = "Kubernetes (Cluster Endpoint)"
contextLocalKubeconfig ContextCreationType = "Kubernetes (Local Kubeconfig)"
contextTanzu ContextCreationType = "Tanzu"
)
type ContextCreationType string
const NA = "n/a"
var contextCmd = &cobra.Command{
Use: "context",
Short: "Configure and manage contexts for the Tanzu CLI",
Aliases: []string{"ctx", "contexts"},
Annotations: map[string]string{
"group": string(plugin.SystemCmdGroup),
},
}
func init() {
contextCmd.SetUsageFunc(cli.SubCmdUsageFunc)
contextCmd.AddCommand(
createCtxCmd,
listCtxCmd,
getCtxCmd,
newCurrentCtxCmd(),
deleteCtxCmd,
useCtxCmd,
unsetCtxCmd,
getCtxTokenCmd,
newUpdateCtxCmd(),
)
initCreateCtxCmd()
listCtxCmd.Flags().StringVarP(&targetStr, "target", "", "", "list only contexts associated with the specified target (kubernetes[k8s]/mission-control[tmc])")
utils.PanicOnErr(listCtxCmd.RegisterFlagCompletionFunc("target", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{compK8sContextType, compTMCContextType}, cobra.ShellCompDirectiveNoFileComp
}))
listCtxCmd.Flags().StringVarP(&contextTypeStr, "type", "t", "", "list only contexts associated with the specified context-type (kubernetes[k8s]/mission-control[tmc]/tanzu)")
utils.PanicOnErr(listCtxCmd.RegisterFlagCompletionFunc("type", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{compK8sContextType, compTanzuContextType, compTMCContextType}, cobra.ShellCompDirectiveNoFileComp
}))
listCtxCmd.Flags().BoolVar(&onlyCurrent, "current", false, "list only current active contexts")
listCtxCmd.Flags().BoolVar(&showAllColumns, "wide", false, "display additional columns for the contexts")
listCtxCmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "output format: table|yaml|json")
utils.PanicOnErr(listCtxCmd.RegisterFlagCompletionFunc("output", completionGetOutputFormats))
getCtxCmd.Flags().StringVarP(&getOutputFmt, "output", "o", "yaml", "output format: yaml|json")
utils.PanicOnErr(getCtxCmd.RegisterFlagCompletionFunc("output", completionGetOutputFormats))
deleteCtxCmd.Flags().BoolVarP(&unattended, "yes", "y", false, "delete the context entry without confirmation")
unsetCtxCmd.Flags().StringVarP(&targetStr, "target", "", "", "unset active context associated with the specified target (kubernetes[k8s]|mission-control[tmc])")
utils.PanicOnErr(unsetCtxCmd.RegisterFlagCompletionFunc("target", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{compK8sContextType, compTMCContextType}, cobra.ShellCompDirectiveNoFileComp
}))
unsetCtxCmd.Flags().StringVarP(&contextTypeStr, "type", "t", "", "unset active context associated with the specified context-type (kubernetes[k8s]|mission-control[tmc]|tanzu)")
utils.PanicOnErr(unsetCtxCmd.RegisterFlagCompletionFunc("type", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{compK8sContextType, compTanzuContextType, compTMCContextType}, cobra.ShellCompDirectiveNoFileComp
}))
msg := "this was done in the v1.1.0 release, it will be removed following the deprecation policy (6 months). Use the --type flag instead.\n"
utils.PanicOnErr(listCtxCmd.Flags().MarkDeprecated("target", msg))
utils.PanicOnErr(unsetCtxCmd.Flags().MarkDeprecated("target", msg))
}
var createCtxCmd = &cobra.Command{
Use: "create CONTEXT_NAME",
Short: "Create a Tanzu CLI context",
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: completeCreateCtx,
RunE: createCtx,
Example: `
# Create a TKG management cluster context using endpoint and type (--type is optional, if not provided the CLI will infer the type from the endpoint)
tanzu context create mgmt-cluster --endpoint https://k8s.example.com[:port] --type k8s
# Create a TKG management cluster context using endpoint
tanzu context create mgmt-cluster --endpoint https://k8s.example.com[:port]
# Create a TKG management cluster context using kubeconfig path and context
tanzu context create mgmt-cluster --kubeconfig path/to/kubeconfig --kubecontext kubecontext
# Create a TKG management cluster context by using the provided CA Bundle for TLS verification:
tanzu context create mgmt-cluster --endpoint https://k8s.example.com[:port] --endpoint-ca-certificate /path/to/ca/ca-cert
# Create a TKG management cluster context by explicit request to skip TLS verification, which is insecure:
tanzu context create mgmt-cluster --endpoint https://k8s.example.com[:port] --insecure-skip-tls-verify
# Create a TKG management cluster context using default kubeconfig path and a kubeconfig context
tanzu context create mgmt-cluster --kubecontext kubecontext
# Create a TMC(mission-control) context using endpoint and type
tanzu context create mytmc --endpoint tmc.example.com:443 --type tmc
# Create a Tanzu context with the default endpoint (--type is not necessary for the default endpoint)
tanzu context create mytanzu --endpoint https://api.tanzu.cloud.vmware.com
# Create a Tanzu context (--type is needed for a non-default endpoint)
tanzu context create mytanzu --endpoint https://non-default.tanzu.endpoint.com --type tanzu
# Create a Tanzu context by using the provided CA Bundle for TLS verification:
tanzu context create mytanzu --endpoint https://api.tanzu.cloud.vmware.com --endpoint-ca-certificate /path/to/ca/ca-cert
# Create a Tanzu context but skip TLS verification (this is insecure):
tanzu context create mytanzu --endpoint https://api.tanzu.cloud.vmware.com --insecure-skip-tls-verify
Notes:
1. TMC context: To create Mission Control (TMC) context an API Key is required. It can be provided using the
TANZU_API_TOKEN environment variable or entered during context creation.
2. Tanzu context: To create Tanzu context an API Key is optional. If provided using the TANZU_API_TOKEN environment
variable, it will be used. Otherwise, the CLI will attempt to log in interactively to the user's default Cloud Services
organization. You can override or choose a custom organization by setting the TANZU_CLI_CLOUD_SERVICES_ORGANIZATION_ID
environment variable with the custom organization ID value. More information regarding organizations in Cloud Services
and how to obtain the organization ID can be found at
https://docs.vmware.com/en/VMware-Cloud-services/services/Using-VMware-Cloud-Services/GUID-CF9E9318-B811-48CF-8499-9419997DC1F8.html
Also, more information on creating tanzu context and using interactive login in terminal based hosts (without browser) can be found at
https://github.com/vmware-tanzu/tanzu-cli/blob/main/docs/quickstart/quickstart.md#creating-and-connecting-to-a-new-context
[*] : Users have two options to create a kubernetes cluster context. They can choose the control
plane option by providing 'endpoint', or use the kubeconfig for the cluster by providing
'kubeconfig' and 'context'. If only '--context' is set and '--kubeconfig' is not, the
$KUBECONFIG env variable will be used and, if the $KUBECONFIG env is also not set, the default
kubeconfig file ($HOME/.kube/config) will be used.`,
}
func initCreateCtxCmd() {
createCtxCmd.Flags().StringVar(&ctxName, "name", "", "name of the context")
utils.PanicOnErr(createCtxCmd.Flags().MarkDeprecated("name", "it has been replaced by using an argument to the command"))
createCtxCmd.Flags().StringVar(&endpoint, "endpoint", "", "endpoint to create a context for")
utils.PanicOnErr(createCtxCmd.RegisterFlagCompletionFunc("endpoint", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return cobra.AppendActiveHelp(nil, "Please enter the endpoint for which to create the context"), cobra.ShellCompDirectiveNoFileComp
}))
createCtxCmd.Flags().StringVar(&apiToken, "api-token", "", "API token for the SaaS context")
utils.PanicOnErr(createCtxCmd.RegisterFlagCompletionFunc("api-token", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return cobra.AppendActiveHelp(nil, fmt.Sprintf("Please enter your api-token (you can instead set the variable %s)", config.EnvAPITokenKey)), cobra.ShellCompDirectiveNoFileComp
}))
// Shell completion for this flag is the default behavior of doing file completion
createCtxCmd.Flags().StringVar(&kubeConfig, "kubeconfig", "", "path to the kubeconfig file; valid only if user doesn't choose 'endpoint' option.(See [*])")
createCtxCmd.Flags().StringVar(&kubeContext, "kubecontext", "", "the context in the kubeconfig to use; valid only if user doesn't choose 'endpoint' option.(See [*]) ")
utils.PanicOnErr(createCtxCmd.RegisterFlagCompletionFunc("kubecontext", completeKubeContext))
createCtxCmd.Flags().BoolVar(&stderrOnly, "stderr-only", false, "send all output to stderr rather than stdout")
createCtxCmd.Flags().BoolVar(&forceCSP, "force-csp", false, "force the context to use CSP auth")
createCtxCmd.Flags().BoolVar(&staging, "staging", false, "use CSP staging issuer")
// Shell completion for this flag is the default behavior of doing file completion
createCtxCmd.Flags().StringVar(&endpointCACertPath, "endpoint-ca-certificate", "", "path to the endpoint public certificate")
createCtxCmd.Flags().BoolVar(&skipTLSVerify, "insecure-skip-tls-verify", false, "skip endpoint's TLS certificate verification")
createCtxCmd.Flags().StringVarP(&contextTypeStr, "type", "t", "", "type of context to create (kubernetes[k8s]/mission-control[tmc]/tanzu)")
utils.PanicOnErr(createCtxCmd.RegisterFlagCompletionFunc("type", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{compK8sContextType, compTanzuContextType, compTMCContextType}, cobra.ShellCompDirectiveNoFileComp
}))
utils.PanicOnErr(createCtxCmd.Flags().MarkHidden("api-token"))
utils.PanicOnErr(createCtxCmd.Flags().MarkHidden("stderr-only"))
utils.PanicOnErr(createCtxCmd.Flags().MarkHidden("force-csp"))
utils.PanicOnErr(createCtxCmd.Flags().MarkHidden("staging"))
createCtxCmd.MarkFlagsMutuallyExclusive("endpoint", "kubecontext")
createCtxCmd.MarkFlagsMutuallyExclusive("endpoint", "kubeconfig")
createCtxCmd.MarkFlagsMutuallyExclusive("endpoint-ca-certificate", "insecure-skip-tls-verify")
}
func createCtx(cmd *cobra.Command, args []string) (err error) {
// The context name is an optional argument to allow for the prompt to be used
if len(args) > 0 {
if ctxName != "" {
return fmt.Errorf("cannot specify the context name as an argument and with the --name flag at the same time")
}
ctxName = args[0]
}
if !configtypes.IsValidContextType(contextTypeStr) {
return errors.New(invalidContextType)
}
ctx, err := createNewContext()
if err != nil {
return err
}
if ctx.ContextType == configtypes.ContextTypeK8s {
err = k8sLogin(ctx)
} else if ctx.ContextType == configtypes.ContextTypeTanzu {
// Tanzu control plane login
err = globalTanzuLogin(ctx, nil)
} else {
err = globalLogin(ctx)
}
if err != nil {
return err
}
// TODO: update the below conditional check (and in login command) after context scope plugin support
// is implemented for tanzu context(TAP SaaS)
// Sync all required plugins
if ctx.ContextType != configtypes.ContextTypeTanzu {
if err := syncContextPlugins(cmd, ctx.ContextType, ctxName); err != nil {
log.Warningf("unable to automatically sync the plugins recommended by the new context. Please run 'tanzu plugin sync' to sync plugins manually, error: '%v'", err.Error())
}
}
return nil
}
// syncContextPlugins syncs the plugins for the given context type
func syncContextPlugins(cmd *cobra.Command, contextType configtypes.ContextType, ctxName string) error {
disablePluginSync, _ := strconv.ParseBool(os.Getenv(constants.SkipAutoInstallOfContextRecommendedPlugins))
if disablePluginSync {
return nil
}
plugins, err := pluginmanager.DiscoverPluginsForContextType(contextType)
if err != nil {
return err
}
if len(plugins) == 0 {
log.Success("No recommended plugins found.")
return nil
}
// update plugins installation status
pluginmanager.UpdatePluginsInstallationStatus(plugins)
// sort the plugins based on the plugin name
sort.Sort(discovery.DiscoveredSorter(plugins))
pluginsNeedToBeInstalled := []discovery.Discovered{}
for idx := range plugins {
if plugins[idx].Status == common.PluginStatusNotInstalled || plugins[idx].Status == common.PluginStatusUpdateAvailable {
pluginsNeedToBeInstalled = append(pluginsNeedToBeInstalled, plugins[idx])
}
}
if len(pluginsNeedToBeInstalled) == 0 {
log.Success("All recommended plugins are already installed and up-to-date.")
return nil
}
errList := make([]error, 0)
log.Infof("Installing the following plugins recommended by context '%s':", ctxName)
displayToBeInstalledPluginsAsTable(plugins, cmd.ErrOrStderr())
for i := range pluginsNeedToBeInstalled {
err = pluginmanager.InstallStandalonePlugin(pluginsNeedToBeInstalled[i].Name, pluginsNeedToBeInstalled[i].RecommendedVersion, pluginsNeedToBeInstalled[i].Target)
if err != nil {
errList = append(errList, err)
}
}
err = kerrors.NewAggregate(errList)
if err == nil {
log.Success("Successfully installed all recommended plugins.")
}
return err
}
// displayToBeInstalledPluginsAsTable takes a list of plugins and displays the plugin info as a table
func displayToBeInstalledPluginsAsTable(plugins []discovery.Discovered, writer io.Writer) {
outputPlugins := component.NewOutputWriterWithOptions(writer, outputFormat, []component.OutputWriterOption{}, "Name", "Target", "Current", "Installing")
outputPlugins.MarkDynamicKeys("Current")
for i := range plugins {
if plugins[i].Status == common.PluginStatusNotInstalled || plugins[i].Status == common.PluginStatusUpdateAvailable {
outputPlugins.AddRow(plugins[i].Name, plugins[i].Target, plugins[i].InstalledVersion, plugins[i].RecommendedVersion)
}
}
outputPlugins.Render()
}
func isGlobalContext(endpoint string) bool {
if strings.Contains(endpoint, knownGlobalHost) {
return true
}
if forceCSP {
return true
}
return false
}
func isGlobalTanzuEndpoint(endpoint string) bool {
for _, hostStr := range []string{"api.tanzu.cloud.vmware.com", "api.tanzu-dev.cloud.vmware.com", "api.tanzu-stable.cloud.vmware.com "} {
if strings.Contains(endpoint, hostStr) {
return true
}
}
return false
}
func getPromptOpts() []component.PromptOpt {
var promptOpts []component.PromptOpt
if stderrOnly {
// This uses stderr because it needs to work inside the kubectl exec plugin flow where stdout is reserved.
promptOpts = append(promptOpts, component.WithStdio(os.Stdin, os.Stderr, os.Stderr))
}
// Add default validations, required
promptOpts = append(promptOpts, component.WithValidator(survey.Required), component.WithValidator(component.NoOnlySpaces))
return promptOpts
}
func createNewContext() (context *configtypes.Context, err error) {
var ctxCreationType ContextCreationType
contextType := getContextType()
if (contextType == configtypes.ContextTypeTanzu) || (endpoint != "" && isGlobalTanzuEndpoint(endpoint)) {
ctxCreationType = contextTanzu
} else if (contextType == configtypes.ContextTypeTMC) || (endpoint != "" && isGlobalContext(endpoint)) {
ctxCreationType = contextMissionControl
} else if endpoint != "" {
// user provided command line option endpoint is provided that is not globalTanzu or GlobalContext=> it is Kubernetes(Cluster Endpoint) type
ctxCreationType = contextK8SClusterEndpoint
} else if kubeContext != "" {
// user provided command line option kubeContext is provided => it is Kubernetes(Local Kubeconfig) type
ctxCreationType = contextLocalKubeconfig
} else if contextType == configtypes.ContextTypeK8s {
// If user provided only command line option type as "kubernetes" without any other flags to infer
// ask user for kubernetes context type("Cluster Endpoint" or "Local Kubeconfig")
ctxCreationType, err = promptKubernetesContextType()
if err != nil {
return context, err
}
}
// if user not provided command line options to infer cluster creation type, prompt user
if ctxCreationType == "" {
ctxCreationType, err = promptContextType()
if err != nil {
return context, err
}
}
return createContextUsingContextType(ctxCreationType)
}
func createContextUsingContextType(ctxCreationType ContextCreationType) (context *configtypes.Context, err error) {
var ctxCreateFunc func() (*configtypes.Context, error)
switch ctxCreationType {
case contextMissionControl:
ctxCreateFunc = createContextWithTMCEndpoint
case contextK8SClusterEndpoint:
ctxCreateFunc = createContextWithClusterEndpoint
case contextLocalKubeconfig:
ctxCreateFunc = createContextWithKubeconfig
case contextTanzu:
ctxCreateFunc = createContextWithTanzuEndpoint
}
return ctxCreateFunc()
}
func createContextWithKubeconfig() (context *configtypes.Context, err error) {
promptOpts := getPromptOpts()
if kubeConfig == "" && kubeContext == "" {
err = component.Prompt(
&component.PromptConfig{
Message: "Enter path to kubeconfig (if any)",
},
&kubeConfig,
promptOpts...,
)
if err != nil {
return context, err
}
} else if kubeConfig == "" {
kubeConfig = kubecfg.GetDefaultKubeConfigFile()
}
kubeConfig = strings.TrimSpace(kubeConfig)
if kubeConfig != "" && kubeContext == "" {
err = component.Prompt(
&component.PromptConfig{
Message: "Enter kube context to use",
},
&kubeContext,
promptOpts...,
)
if err != nil {
return context, err
}
}
kubeContext = strings.TrimSpace(kubeContext)
if ctxName == "" {
err = component.Prompt(
&component.PromptConfig{
Message: "Give the context a name",
},
&ctxName,
promptOpts...,
)
if err != nil {
return context, err
}
}
ctxName = strings.TrimSpace(ctxName)
exists, err := config.ContextExists(ctxName)
if err != nil {
return context, err
}
if exists {
err = fmt.Errorf("context %q already exists", ctxName)
return context, err
}
context = &configtypes.Context{
Name: ctxName,
ContextType: configtypes.ContextTypeK8s,
ClusterOpts: &configtypes.ClusterServer{
Path: kubeConfig,
Context: kubeContext,
Endpoint: endpoint,
IsManagementCluster: true,
},
}
return context, err
}
func createContextWithTMCEndpoint() (context *configtypes.Context, err error) {
if endpoint == "" {
endpoint, err = promptEndpoint("")
if err != nil {
return context, err
}
}
if ctxName == "" {
ctxName, err = promptContextName("")
if err != nil {
return context, err
}
}
exists, err := config.ContextExists(ctxName)
if err != nil {
return context, err
}
if exists {
err = fmt.Errorf("context %q already exists", ctxName)
return context, err
}
if os.Getenv(constants.E2ETestEnvironment) != "true" && (strings.HasPrefix(endpoint, "https:") || strings.HasPrefix(endpoint, "http:")) {
return nil, errors.Errorf("TMC endpoint URL %s should not contain http or https scheme. It should be of the format host[:port]", endpoint)
}
context = &configtypes.Context{
Name: ctxName,
ContextType: configtypes.ContextTypeTMC,
GlobalOpts: &configtypes.GlobalServer{Endpoint: sanitizeEndpoint(endpoint)},
}
return context, err
}
// createContextWithClusterEndpoint creates context for cluster endpoint with pinniped auth
func createContextWithClusterEndpoint() (context *configtypes.Context, err error) {
if endpoint == "" {
endpoint, err = promptEndpoint("")
if err != nil {
return context, err
}
}
if ctxName == "" {
ctxName, err = promptContextName("")
if err != nil {
return context, err
}
}
exists, err := config.ContextExists(ctxName)
if err != nil {
return context, err
}
if exists {
err = fmt.Errorf("context %q already exists", ctxName)
return context, err
}
// TKGKubeconfigFetcher would detect the endpoint is TKGm/TKGs and then fetch the pinniped kubeconfig to create a context
tkf := NewTKGKubeconfigFetcher(endpoint, endpointCACertPath, skipTLSVerify)
kubeConfig, kubeContext, err = tkf.GetPinnipedKubeconfig()
if err != nil {
return context, err
}
context = &configtypes.Context{
Name: ctxName,
ContextType: configtypes.ContextTypeK8s,
ClusterOpts: &configtypes.ClusterServer{
Path: kubeConfig,
Context: kubeContext,
Endpoint: endpoint,
IsManagementCluster: true,
},
AdditionalMetadata: map[string]interface{}{
isPinnipedEndpoint: true,
},
}
return context, err
}
func createContextWithTanzuEndpoint() (context *configtypes.Context, err error) {
if endpoint == "" {
endpoint, err = promptEndpoint(defaultTanzuEndpoint)
if err != nil {
return context, err
}
}
if ctxName == "" {
ctxName, err = promptContextName("")
if err != nil {
return context, err
}
}
exists, err := config.ContextExists(ctxName)
if err != nil {
return context, err
}
if exists {
err = fmt.Errorf("context %q already exists", ctxName)
return context, err
}
sanitizedEndpoint := sanitizeEndpoint(endpoint)
// Tanzu context would have both CSP(GlobalOpts) auth details and kubeconfig(ClusterOpts),
context = &configtypes.Context{
Name: ctxName,
ContextType: configtypes.ContextTypeTanzu,
GlobalOpts: &configtypes.GlobalServer{Endpoint: sanitizedEndpoint},
ClusterOpts: &configtypes.ClusterServer{},
AdditionalMetadata: map[string]interface{}{
tanzuMissionControlEndpoint: mapTanzuEndpointToTMCEndpoint(sanitizedEndpoint),
},
}
return context, err
}
func globalLogin(c *configtypes.Context) (err error) {
apiTokenValue, apiTokenExists := os.LookupEnv(config.EnvAPITokenKey)
if apiTokenExists {
log.Info("API token env var is set")
} else {
fmt.Fprintln(os.Stderr)
log.Info("The API key can be provided by setting the TANZU_API_TOKEN environment variable")
apiTokenValue, err = promptAPIToken("TMC")
if err != nil {
return err
}
}
_, err = doCSPAPITokenAuthAndUpdateContext(c, apiTokenValue)
if err != nil {
return err
}
err = config.AddContext(c, true)
if err != nil {
return err
}
// format
fmt.Fprintln(os.Stderr)
log.Success("successfully created a TMC context")
return nil
}
func globalTanzuLogin(c *configtypes.Context, generateContextNameFunc func(orgName, endpoint string, isStaging bool) string) error {
claims, err := doCSPAuthentication(c)
if err != nil {
return err
}
orgName, err := getCSPOrganizationName(c, claims)
if err != nil {
return err
}
// Fetch the Tanzu Hub endpoint for the Tanzu context as a best case effort
tanzuHubEndpoint, err := csp.GetTanzuHubEndpoint(claims.OrgID, c.GlobalOpts.Auth.AccessToken, staging)
if err != nil {
log.V(7).Infof("unable to get Tanzu Hub endpoint. Error: %v", err.Error())
}
// update the context name using the context name generator
if generateContextNameFunc != nil {
c.Name = generateContextNameFunc(orgName, endpoint, staging)
}
// update the context metadata
if err := updateTanzuContextMetadata(c, claims.OrgID, orgName, tanzuHubEndpoint); err != nil {
return err
}
// Fetch the tanzu kubeconfig and update context
if err := updateContextWithTanzuKubeconfig(c, endpoint, claims.OrgID, endpointCACertPath, skipTLSVerify); err != nil {
return err
}
// Add the context to configuration
if err := config.AddContext(c, true); err != nil {
return err
}
// update the current context in the kubeconfig file after creating the context
if c.ClusterOpts != nil {
err = syncCurrentKubeContext(c)
if err != nil {
return errors.Wrap(err, "unable to update current kube context")
}
}
// format
fmt.Fprintln(os.Stderr)
log.Successf("Successfully logged into '%s' organization and created a tanzu context", orgName)
// log warning message if the TAP scopes are retrieved successfully and validation failed
valid, err := validateTokenForTAPScopes(claims, nil)
if err == nil && !valid {
logTanzuInvalidOrgWarningMessage(orgName)
}
return nil
}
func logTanzuInvalidOrgWarningMessage(orgName string) {
warnMsg := `WARNING: While authenticated to organization '%s', there are insufficient permissions to access
the Tanzu Application Platform service. Please ensure correct organization authentication and access permissions
`
fmt.Fprintln(os.Stderr)
log.Warningf(warnMsg, orgName)
fmt.Fprintln(os.Stderr)
}
// updateTanzuContextMetadata updates the context additional metadata
func updateTanzuContextMetadata(c *configtypes.Context, orgID, orgName, tanzuHubEndpoint string) error {
exists, err := config.ContextExists(c.Name)
if err != nil {
return err
}
if !exists {
c.AdditionalMetadata[config.OrgIDKey] = orgID
c.AdditionalMetadata[config.OrgNameKey] = orgName
c.AdditionalMetadata[config.TanzuHubEndpointKey] = tanzuHubEndpoint
return nil
}
// This is possible only for contexts created using "tanzu login" command because
// "tanzu context create" command doesn't allow user to create duplicate contexts
existingContext, err := config.GetContext(c.Name)
if err != nil {
return err
}
// If the context exists with the same name, honor the users current context additional metadata
// which includes the org/project/space details.
c.AdditionalMetadata = existingContext.AdditionalMetadata
c.AdditionalMetadata[config.TanzuHubEndpointKey] = tanzuHubEndpoint
return nil
}
// getCSPOrganizationName returns the CSP Org name using the orgID from the claims.
// It will return empty string if API fails
func getCSPOrganizationName(c *configtypes.Context, claims *csp.Claims) (string, error) {
issuer := csp.ProdIssuer
if staging {
issuer = csp.StgIssuer
}
if c.GlobalOpts == nil {
return "", errors.New("invalid context %q. Missing authorization fields")
}
orgName, err := csp.GetOrgNameFromOrgID(claims.OrgID, c.GlobalOpts.Auth.AccessToken, issuer)
if err != nil {
return "", err
}
return orgName, nil
}
func updateContextWithTanzuKubeconfig(c *configtypes.Context, ep, orgID, epCACertPath string, skipTLSVerify bool) error {
kubeCfg, kubeCtx, orgEndpoint, err := tanzuauth.GetTanzuKubeconfig(c, ep, orgID, epCACertPath, skipTLSVerify)
if err != nil {
return err
}
if c.ClusterOpts == nil {
c.ClusterOpts = &configtypes.ClusterServer{}
}
c.ClusterOpts.Path = kubeCfg
c.ClusterOpts.Context = kubeCtx
// for "tanzu" context ClusterOpts.Endpoint would always be pointing to UCP organization endpoint
c.ClusterOpts.Endpoint = orgEndpoint
return nil
}
func doCSPAuthentication(c *configtypes.Context) (*csp.Claims, error) {
apiTokenValue, apiTokenExists := os.LookupEnv(config.EnvAPITokenKey)
// Use API Token login flow if TANZU_API_TOKEN environment variable is set, else fall back to default interactive login flow
if apiTokenExists {
log.Info("API token env var is set")
return doCSPAPITokenAuthAndUpdateContext(c, apiTokenValue)
}
return doCSPInteractiveLoginAndUpdateContext(c)
}
func doCSPInteractiveLoginAndUpdateContext(c *configtypes.Context) (claims *csp.Claims, err error) {
issuer := csp.ProdIssuer
if staging {
issuer = csp.StgIssuer
}
cspOrgIDValue, cspOrgIDExists := os.LookupEnv(constants.CSPLoginOrgID)
var loginOptions []csp.LoginOption
if cspOrgIDExists && cspOrgIDValue != "" {
loginOptions = append(loginOptions, csp.WithOrgID(cspOrgIDValue))
}
// If user chooses to use a specific local listener port, use it
loginOptions = append(loginOptions, csp.WithListenerPortFromEnv(constants.TanzuCLIOAuthLocalListenerPort))
token, err := csp.TanzuLogin(issuer, loginOptions...)
if err != nil {
return nil, errors.Wrap(err, "failed to get the token from CSP")
}
claims, err = csp.ParseToken(&oauth2.Token{AccessToken: token.AccessToken})
if err != nil {
return nil, err
}
a := configtypes.GlobalServerAuth{}
a.Issuer = issuer
a.UserName = claims.Username
a.Permissions = claims.Permissions
a.AccessToken = token.AccessToken
a.IDToken = token.IDToken
a.RefreshToken = token.RefreshToken
a.Type = token.TokenType
expiresAt := time.Now().Local().Add(time.Second * time.Duration(token.ExpiresIn))
a.Expiration = expiresAt
c.GlobalOpts.Auth = a
if c.AdditionalMetadata == nil {
c.AdditionalMetadata = make(map[string]interface{})
}
return claims, nil
}
func doCSPAPITokenAuthAndUpdateContext(c *configtypes.Context, apiTokenValue string) (claims *csp.Claims, err error) {
issuer := csp.ProdIssuer
if staging {
issuer = csp.StgIssuer
}
token, err := csp.GetAccessTokenFromAPIToken(apiTokenValue, issuer)
if err != nil {
return nil, errors.Wrap(err, "failed to get the token from CSP")
}
claims, err = csp.ParseToken(&oauth2.Token{AccessToken: token.AccessToken})
if err != nil {
return nil, err
}
a := configtypes.GlobalServerAuth{}
a.Issuer = issuer
a.UserName = claims.Username
a.Permissions = claims.Permissions
a.AccessToken = token.AccessToken
a.IDToken = token.IDToken
a.RefreshToken = apiTokenValue
a.Type = csp.APITokenType
expiresAt := time.Now().Local().Add(time.Second * time.Duration(token.ExpiresIn))
a.Expiration = expiresAt
c.GlobalOpts.Auth = a
if c.AdditionalMetadata == nil {
c.AdditionalMetadata = make(map[string]interface{})
}
return claims, nil
}
func promptContextType() (ctxCreationType ContextCreationType, err error) {
ctxCreationTypeStr := ""
promptOpts := getPromptOpts()
err = component.Prompt(
&component.PromptConfig{
Message: "Select context creation type",
Options: []string{string(contextTanzu), string(contextMissionControl), string(contextK8SClusterEndpoint), string(contextLocalKubeconfig)},
Default: string(contextTanzu),
},
&ctxCreationTypeStr,
promptOpts...,
)
if err != nil {
return
}
return stringToContextCreationType(ctxCreationTypeStr), nil
}
func stringToContextCreationType(ctxCreationTypeStr string) ContextCreationType {
if ctxCreationTypeStr == string(contextMissionControl) {
return contextMissionControl
} else if ctxCreationTypeStr == string(contextTanzu) {
return contextTanzu
} else if ctxCreationTypeStr == string(contextK8SClusterEndpoint) {
return contextK8SClusterEndpoint
} else if ctxCreationTypeStr == string(contextLocalKubeconfig) {
return contextLocalKubeconfig
}
return ""
}
func promptKubernetesContextType() (ctxCreationType ContextCreationType, err error) {
ctxCreationTypeStr := ""
promptOpts := getPromptOpts()
err = component.Prompt(
&component.PromptConfig{
Message: "Select the kubernetes context type",
Options: []string{string(contextLocalKubeconfig), string(contextK8SClusterEndpoint)},
Default: string(contextLocalKubeconfig),
},
&ctxCreationTypeStr,
promptOpts...,
)
if err != nil {
return
}
return stringToContextCreationType(ctxCreationTypeStr), nil
}
func promptEndpoint(defaultEndpoint string) (ep string, err error) {
promptOpts := getPromptOpts()
err = component.Prompt(
&component.PromptConfig{
Message: "Enter control plane endpoint",
Default: defaultEndpoint,
},
&ep,
promptOpts...,
)
if err != nil {
return
}
ep = strings.TrimSpace(ep)
return
}
func promptContextName(defaultCtxName string) (cname string, err error) {
promptOpts := getPromptOpts()
err = component.Prompt(
&component.PromptConfig{
Message: "Give the context a name",
Default: defaultCtxName,
},
&cname,
promptOpts...,
)
if err != nil {
return
}
cname = strings.TrimSpace(cname)
return
}
// Interactive way to create a TMC context. User will be prompted for CSP API token.
func promptAPIToken(endpointType string) (apiToken string, err error) {
hostVal := "console.cloud.vmware.com"
if staging {
hostVal = "console-stg.cloud.vmware.com"
}
consoleURL := url.URL{
Scheme: "https",
Host: hostVal,
Path: "/csp/gateway/portal/",
Fragment: "/user/tokens",
}
// The below message is applicable for TMC
msg := fmt.Sprintf("If you don't have an API token, visit the VMware Cloud Services console, select your organization, and create an API token with the %s service roles:\n %s\n",
endpointType, consoleURL.String())
// format
fmt.Println()
log.Infof(msg)
promptOpts := getPromptOpts()
// format
fmt.Println()
err = component.Prompt(
&component.PromptConfig{
Message: "API Token",
Sensitive: true,
},
&apiToken,
promptOpts...,
)
apiToken = strings.TrimSpace(apiToken)
return apiToken, err
}
func k8sLogin(c *configtypes.Context) error {
if c != nil && c.ClusterOpts != nil && c.ClusterOpts.Path != "" && c.ClusterOpts.Context != "" {
_, err := tkgauth.GetServerKubernetesVersion(c.ClusterOpts.Path, c.ClusterOpts.Context)
if err != nil {
err := fmt.Errorf("failed to create context %q for a kubernetes cluster, %v", c.Name, err)
log.Error(err, "")
return err
}
err = config.AddContext(c, true)
if err != nil {
return err
}
// update the current context in the kubeconfig file after creating the context
err = syncCurrentKubeContext(c)
if err != nil {
return errors.Wrap(err, "unable to update current kube context")
}
log.Successf("successfully created a kubernetes context using the kubeconfig %s", c.ClusterOpts.Path)
return nil
}
return fmt.Errorf("not yet implemented")
}
func sanitizeEndpoint(endpoint string) string {
if len(strings.Split(endpoint, ":")) == 1 {
return fmt.Sprintf("%s:443", endpoint)
}
return endpoint
}
func getDiscoveryHTTPClient(tlsConfig *tls.Config) *http.Client {
tr := &http.Transport{