diff --git a/cmd/add.go b/cmd/add.go index 78328001..d14ccb02 100644 --- a/cmd/add.go +++ b/cmd/add.go @@ -23,6 +23,7 @@ import ( "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest" + "log" "os" syaml "sigs.k8s.io/yaml" "strings" @@ -50,21 +51,28 @@ kubecm add -f example.yaml -c if fileExists(file) { err := configCheck(file) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } cover, _ = cmd.Flags().GetBool("cover") config, err := getAddConfig(file) if err != nil { - fmt.Println(err) + Error.Println(err) } output := merge2Master(config) err = WriteConfig(output) if err != nil { - fmt.Println(err.Error()) + Error.Println(err.Error()) + } else { + log.Printf("「%s」 add successful!", file) + err = Formatable(nil) + if err != nil { + log.Println(err) + os.Exit(1) + } } } else { - fmt.Printf("%s file does not exist", file) + Error.Printf("%s file does not exist", file) os.Exit(1) } }, @@ -86,14 +94,15 @@ func getAddConfig(kubeconfig string) (*clientcmdapi.Config, error) { } if len(config.AuthInfos) != 1 { - fmt.Println("Only support add 1 context.") + //fmt.Println("Only support add 1 context.") + Error.Println("Only support add 1 context.") os.Exit(-1) } name := getName() err = nameCheck(name) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(-1) } suffix := HashSuf(config) @@ -192,11 +201,11 @@ func merge2Master(config *clientcmdapi.Config) []byte { json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) if err != nil { - fmt.Printf("Unexpected error: %v", err) + Error.Printf("Unexpected error: %v", err) } output, err := syaml.JSONToYAML(json) if err != nil { - fmt.Printf("Unexpected error: %v", err) + Error.Printf("Unexpected error: %v", err) } return output diff --git a/cmd/delete.go b/cmd/delete.go index 25481a8e..cb41f6a7 100644 --- a/cmd/delete.go +++ b/cmd/delete.go @@ -19,6 +19,7 @@ import ( "fmt" "github.com/spf13/cobra" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "log" "os" ) @@ -40,7 +41,7 @@ var deleteCmd = &cobra.Command{ } err = deleteContext(args, config) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(-1) } } else { @@ -55,19 +56,18 @@ func init() { } func deleteContext(ctxs []string, config *clientcmdapi.Config) error { - for key, _ := range config.Contexts { - for _, ctx := range ctxs { - if ctx == key { - delete(config.Contexts, key) - break - } + for _, ctx := range ctxs { + if _, ok := config.Contexts[ctx]; ok { + delete(config.Contexts, ctx) + log.Printf("Context Delete: %s \n", ctx) + } else { + Error.Printf("「%s」do not exit.", ctx) } } err := ModifyKubeConfig(config) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } - fmt.Printf("Context delete succeeded!\nDelete: %v \n", ctxs) return nil } diff --git a/cmd/get.go b/cmd/get.go index f23bbdce..34860cfb 100644 --- a/cmd/get.go +++ b/cmd/get.go @@ -17,7 +17,6 @@ package cmd import ( "fmt" - "github.com/bndr/gotabulate" "github.com/spf13/cobra" "os" ) @@ -25,8 +24,8 @@ import ( // getCmd represents the get command var getCmd = &cobra.Command{ Use: "get", - Short: "Displays one or many contexts from the kubeconfig file", - Long: `Displays one or many contexts from the kubeconfig file`, + Short: "Displays one or many contexts from the kubeconfig file(Will be removed in new version, move to kubecm)", + Long: `Displays one or many contexts from the kubeconfig file(Will be removed in new version, move to kubecm)`, Example: ` # List all the contexts in your kubeconfig file kubecm get @@ -35,6 +34,7 @@ var getCmd = &cobra.Command{ kubecm get my-context `, Run: func(cmd *cobra.Command, args []string) { + Warning.Println("This command Will be removed in new version, move to kubecm.") if len(args) == 0 { err := Formatable(nil) if err != nil { @@ -60,50 +60,50 @@ func init() { getCmd.SetArgs([]string{""}) } -func Formatable(args []string) error { - config, err := LoadClientConfig(cfgFile) - if err != nil { - return err - } - var table [][]string - if args == nil { - for key, obj := range config.Contexts { - var tmp []string - if config.CurrentContext == key { - tmp = append(tmp, "*") - } else { - tmp = append(tmp, "") - } - tmp = append(tmp, key) - tmp = append(tmp, obj.Cluster) - tmp = append(tmp, obj.AuthInfo) - tmp = append(tmp, obj.Namespace) - table = append(table, tmp) - } - } else { - for key, obj := range config.Contexts { - var tmp []string - if config.CurrentContext == key { - tmp = append(tmp, "*") - tmp = append(tmp, key) - tmp = append(tmp, obj.Cluster) - tmp = append(tmp, obj.AuthInfo) - tmp = append(tmp, obj.Namespace) - table = append(table, tmp) - } - } - } - - if table != nil { - tabulate := gotabulate.Create(table) - tabulate.SetHeaders([]string{"CURRENT", "NAME", "CLUSTER", "USER", "Namespace"}) - // Turn On String Wrapping - tabulate.SetWrapStrings(true) - // Render the table - tabulate.SetAlign("center") - fmt.Println(tabulate.Render("grid", "left")) - } else { - return fmt.Errorf("context %v not found", args) - } - return nil -} +//func Formatable(args []string) error { +// config, err := LoadClientConfig(cfgFile) +// if err != nil { +// return err +// } +// var table [][]string +// if args == nil { +// for key, obj := range config.Contexts { +// var tmp []string +// if config.CurrentContext == key { +// tmp = append(tmp, "*") +// } else { +// tmp = append(tmp, "") +// } +// tmp = append(tmp, key) +// tmp = append(tmp, obj.Cluster) +// tmp = append(tmp, obj.AuthInfo) +// tmp = append(tmp, obj.Namespace) +// table = append(table, tmp) +// } +// } else { +// for key, obj := range config.Contexts { +// var tmp []string +// if config.CurrentContext == key { +// tmp = append(tmp, "*") +// tmp = append(tmp, key) +// tmp = append(tmp, obj.Cluster) +// tmp = append(tmp, obj.AuthInfo) +// tmp = append(tmp, obj.Namespace) +// table = append(table, tmp) +// } +// } +// } +// +// if table != nil { +// tabulate := gotabulate.Create(table) +// tabulate.SetHeaders([]string{"CURRENT", "NAME", "CLUSTER", "USER", "Namespace"}) +// // Turn On String Wrapping +// tabulate.SetWrapStrings(true) +// // Render the table +// tabulate.SetAlign("center") +// fmt.Println(tabulate.Render("grid", "left")) +// } else { +// return fmt.Errorf("context %v not found", args) +// } +// return nil +//} diff --git a/cmd/merge.go b/cmd/merge.go index bc90440d..e736f010 100644 --- a/cmd/merge.go +++ b/cmd/merge.go @@ -22,6 +22,7 @@ import ( "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest" + "log" "os" "sigs.k8s.io/yaml" "strings" @@ -46,8 +47,9 @@ kubecm merge -f test -c Run: func(cmd *cobra.Command, args []string) { cover, _ = cmd.Flags().GetBool("cover") files := listFile(folder) - fmt.Printf("Loading kubeconfig file: %v \n", files) + log.Printf("Loading kubeconfig file: %v \n", files) var loop []string + var defaultName string for _, yaml := range files { config, err := LoadClientConfig(yaml) if err != nil { @@ -85,18 +87,23 @@ kubecm merge -f test -c } _ = clientcmd.WriteToFile(configType, commandLineFile.Name()) loop = append(loop, commandLineFile.Name()) + log.Printf("Context Add: %s \n", name) + defaultName = name } loadingRules := &clientcmd.ClientConfigLoadingRules{ Precedence: loop, } mergedConfig, err := loadingRules.Load() + if mergedConfig != nil { + mergedConfig.CurrentContext = defaultName + } json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) if err != nil { - fmt.Printf("Unexpected error: %v", err) + Error.Printf("Unexpected error: %v", err) } output, err := yaml.JSONToYAML(json) if err != nil { - fmt.Printf("Unexpected error: %v", err) + Error.Printf("Unexpected error: %v", err) } for _, name := range loop { @@ -105,7 +112,7 @@ kubecm merge -f test -c err = WriteConfig(output) if err != nil { - fmt.Println(err.Error()) + Error.Println(err.Error()) } }, } diff --git a/cmd/rename.go b/cmd/rename.go index 074bab28..72a2f1cd 100644 --- a/cmd/rename.go +++ b/cmd/rename.go @@ -16,8 +16,8 @@ limitations under the License. package cmd import ( - "fmt" "github.com/spf13/cobra" + "log" "os" ) @@ -37,12 +37,16 @@ kubecm rename -n dev -c Run: func(cmd *cobra.Command, args []string) { cover, _ = cmd.Flags().GetBool("cover") if cover && oldName != "" { - fmt.Println("parameter `-c` and `-n` cannot be set at the same time") + log.Println("parameter `-c` and `-n` cannot be set at the same time") os.Exit(1) } else { config, err := LoadClientConfig(cfgFile) if err != nil { - fmt.Println(err) + Error.Println(err) + os.Exit(-1) + } + if _, ok := config.Contexts[newName]; ok { + Error.Printf("the name:%s is exit.",newName) os.Exit(-1) } if cover { @@ -51,7 +55,7 @@ kubecm rename -n dev -c config.Contexts[newName] = obj delete(config.Contexts, key) config.CurrentContext = newName - fmt.Println(fmt.Sprintf("Rename %s to %s", key, newName)) + log.Printf("Rename %s to %s", key, newName) break } } @@ -63,10 +67,10 @@ kubecm rename -n dev -c config.CurrentContext = newName } } else { - fmt.Println(fmt.Sprintf("Can not find context: %s", oldName)) + log.Printf("Can not find context: %s", oldName) err := Formatable(nil) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } os.Exit(-1) @@ -74,13 +78,13 @@ kubecm rename -n dev -c } err = ModifyKubeConfig(config) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } } err := Formatable(nil) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } }, diff --git a/cmd/root.go b/cmd/root.go index e35bafc2..ea212062 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -18,13 +18,21 @@ package cmd import ( "flag" "fmt" + "github.com/bndr/gotabulate" "github.com/spf13/cobra" + "log" "os" "path/filepath" ) var cfgFile string +var ( + Info *log.Logger + Warning *log.Logger + Error *log.Logger +) + var rootCmd = &cobra.Command{ Use: "kubecm", Short: "KubeConfig Manager.", @@ -38,6 +46,29 @@ KubeConfig Manager Find more information at: https://github.com/sunny0826/kubecm `, + Example: ` +# List all the contexts in your kubeconfig file +kubecm +`, + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + err := Formatable(nil) + if err != nil { + Error.Println(err) + os.Exit(1) + } + } else { + err := Formatable(args) + if err != nil { + Error.Println(err) + os.Exit(1) + } + } + err := ClusterStatus() + if err != nil { + log.Printf("Cluster check failure!\n%v", err) + } + }, } func Execute() { @@ -49,6 +80,9 @@ func Execute() { func init() { cobra.OnInitialize(initConfig) + Info = log.New(os.Stdout, "Info:", log.Ldate|log.Ltime|log.Lshortfile) + Warning = log.New(os.Stdout, "Warning:", log.Ldate|log.Ltime|log.Lshortfile) + Error = log.New(os.Stderr, "Error:", log.Ldate|log.Ltime|log.Lshortfile) } func initConfig() { @@ -62,3 +96,51 @@ func homeDir() string { } return os.Getenv("USERPROFILE") // windows } + +func Formatable(args []string) error { + config, err := LoadClientConfig(cfgFile) + if err != nil { + return err + } + var table [][]string + if args == nil { + for key, obj := range config.Contexts { + var tmp []string + if config.CurrentContext == key { + tmp = append(tmp, "*") + } else { + tmp = append(tmp, "") + } + tmp = append(tmp, key) + tmp = append(tmp, obj.Cluster) + tmp = append(tmp, obj.AuthInfo) + tmp = append(tmp, obj.Namespace) + table = append(table, tmp) + } + } else { + for key, obj := range config.Contexts { + var tmp []string + if config.CurrentContext == key { + tmp = append(tmp, "*") + tmp = append(tmp, key) + tmp = append(tmp, obj.Cluster) + tmp = append(tmp, obj.AuthInfo) + tmp = append(tmp, obj.Namespace) + table = append(table, tmp) + } + } + } + + if table != nil { + tabulate := gotabulate.Create(table) + tabulate.SetHeaders([]string{"CURRENT", "NAME", "CLUSTER", "USER", "Namespace"}) + // Turn On String Wrapping + tabulate.SetWrapStrings(true) + // Render the table + tabulate.SetAlign("center") + fmt.Println(tabulate.Render("grid", "left")) + } else { + return fmt.Errorf("context %v not found", args) + } + return nil +} diff --git a/cmd/switch.go b/cmd/switch.go index 51d9643d..1c5a4cdf 100644 --- a/cmd/switch.go +++ b/cmd/switch.go @@ -17,19 +17,18 @@ package cmd import ( "fmt" - "os" - "strings" - "github.com/manifoldco/promptui" "github.com/spf13/cobra" + "io/ioutil" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "log" + "os" + "strings" ) -type pepper struct { - Name string - HeatUnit int - Peppers int -} - type needle struct { Name string Cluster string @@ -50,7 +49,7 @@ Switch Kube Context interactively. Run: func(cmd *cobra.Command, args []string) { config, err := LoadClientConfig(cfgFile) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(-1) } @@ -95,20 +94,20 @@ Switch Kube Context interactively. i, _, err := prompt.Run() kubeName := kubeItems[i].Name if err != nil { - fmt.Printf("Prompt failed %v\n", err) + log.Printf("Prompt failed %v\n", err) return } config.CurrentContext = kubeName err = ModifyKubeConfig(config) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } - fmt.Printf("Switched to context %s\n", kubeName) + log.Printf("Switched to context %s\n", kubeName) err = Formatable(nil) if err != nil { - fmt.Println(err) + Error.Println(err) os.Exit(1) } }, @@ -117,3 +116,44 @@ Switch Kube Context interactively. func init() { rootCmd.AddCommand(switchCmd) } + +func ModifyKubeConfig(config *clientcmdapi.Config) error { + commandLineFile, _ := ioutil.TempFile("", "") + defer os.Remove(commandLineFile.Name()) + configType := clientcmdapi.Config{ + AuthInfos: config.AuthInfos, + Clusters: config.Clusters, + Contexts: config.Contexts, + } + _ = clientcmd.WriteToFile(configType, commandLineFile.Name()) + pathOptions := clientcmd.NewDefaultPathOptions() + + if err := clientcmd.ModifyConfig(pathOptions, *config, true); err != nil { + log.Println("Unexpected error: %v", err) + return err + } + return nil +} + +func ClusterStatus() error { + config, err := clientcmd.BuildConfigFromFlags("", cfgFile) + if err != nil { + return fmt.Errorf(err.Error()) + } + + clientset, err := kubernetes.NewForConfig(config) + if err != nil { + return fmt.Errorf(err.Error()) + } + + cus, err := clientset.CoreV1().ComponentStatuses().List(metav1.ListOptions{}) + if err != nil { + return fmt.Errorf(err.Error()) + } + var names []string + for _, k := range cus.Items { + names = append(names, k.Name) + } + log.Printf("Cluster check succeeded!\nContains components: %v \n", names) + return nil +} diff --git a/cmd/use.go b/cmd/use.go index b6ee60ee..0aaf8d5e 100644 --- a/cmd/use.go +++ b/cmd/use.go @@ -18,26 +18,22 @@ package cmd import ( "fmt" "github.com/spf13/cobra" - "io/ioutil" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "os" ) // useCmd represents the use command var useCmd = &cobra.Command{ Use: "use", - Short: "Sets the current-context in a kubeconfig file", + Short: "Sets the current-context in a kubeconfig file(Will be removed in new version, please use kubecm swtich)", Example: ` # Use the context for the test cluster kubecm use test `, Long: ` -Sets the current-context in a kubeconfig file +Sets the current-context in a kubeconfig file(Will be removed in new version, please use kubecm swtich) `, Run: func(cmd *cobra.Command, args []string) { + Warning.Println("This command Will be removed in new version, please use kubecm swtich.") if len(args) == 1 { context := args[0] config, err := LoadClientConfig(cfgFile) @@ -78,44 +74,3 @@ func init() { rootCmd.AddCommand(useCmd) useCmd.SetArgs([]string{""}) } - -func ModifyKubeConfig(config *clientcmdapi.Config) error { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - configType := clientcmdapi.Config{ - AuthInfos: config.AuthInfos, - Clusters: config.Clusters, - Contexts: config.Contexts, - } - _ = clientcmd.WriteToFile(configType, commandLineFile.Name()) - pathOptions := clientcmd.NewDefaultPathOptions() - - if err := clientcmd.ModifyConfig(pathOptions, *config, true); err != nil { - fmt.Println("Unexpected error: %v", err) - return err - } - return nil -} - -func ClusterStatus() error { - config, err := clientcmd.BuildConfigFromFlags("", cfgFile) - if err != nil { - return fmt.Errorf(err.Error()) - } - - clientset, err := kubernetes.NewForConfig(config) - if err != nil { - return fmt.Errorf(err.Error()) - } - - cus, err := clientset.CoreV1().ComponentStatuses().List(metav1.ListOptions{}) - if err != nil { - return fmt.Errorf(err.Error()) - } - var names []string - for _, k := range cus.Items { - names = append(names, k.Name) - } - fmt.Printf("Cluster check succeeded!\nContains components: %v \n", names) - return nil -} diff --git a/cmd/hasher.go b/cmd/utils.go similarity index 100% rename from cmd/hasher.go rename to cmd/utils.go