kubectl源码分析之config get-contexts

发布一个k8s部署视频:https://edu.csdn.net/course/detail/26967

课程内容:各种k8s部署方式。包括minikube部署,kubeadm部署,kubeasz部署,rancher部署,k3s部署。包括开发测试环境部署k8s,和生产环境部署k8s。

腾讯课堂连接地址https://ke.qq.com/course/478827?taid=4373109931462251&tuin=ba64518

第二个视频发布  https://edu.csdn.net/course/detail/27109

腾讯课堂连接地址https://ke.qq.com/course/484107?tuin=ba64518

介绍主要的k8s资源的使用配置和命令。包括configmap,pod,service,replicaset,namespace,deployment,daemonset,ingress,pv,pvc,sc,role,rolebinding,clusterrole,clusterrolebinding,secret,serviceaccount,statefulset,job,cronjob,podDisruptionbudget,podSecurityPolicy,networkPolicy,resourceQuota,limitrange,endpoint,event,conponentstatus,node,apiservice,controllerRevision等。

第三个视频发布:https://edu.csdn.net/course/detail/27574

详细介绍helm命令,学习helm chart语法,编写helm chart。深入分析各项目源码,学习编写helm插件

第四个课程发布:https://edu.csdn.net/course/detail/28488

本课程将详细介绍k8s所有命令,以及命令的go源码分析,学习知其然,知其所以然
————————————————

type GetContextsOptions struct {//get-contexts结构体
	configAccess clientcmd.ConfigAccess
	nameOnly     bool
	showHeaders  bool
	contextNames []string

	genericclioptions.IOStreams
}
//创建get-contexts命令
func NewCmdConfigGetContexts(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command {
	options := &GetContextsOptions{//初始化结构体
		configAccess: configAccess,

		IOStreams: streams,
	}

	cmd := &cobra.Command{//创建cobra命令
		Use:                   "get-contexts [(-o|--output=)name)]",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Describe one or many contexts"),
		Long:                  getContextsLong,
		Example:               getContextsExample,
		Run: func(cmd *cobra.Command, args []string) {
			validOutputTypes := sets.NewString("", "json", "yaml", "wide", "name", "custom-columns", "custom-columns-file", "go-template", "go-template-file", "jsonpath", "jsonpath-file")//有效的输出格式
			supportedOutputTypes := sets.NewString("", "name")//支持的输出格式
			outputFormat := cmdutil.GetFlagString(cmd, "output")//获取输出格式
			if !validOutputTypes.Has(outputFormat) {//判断输出是否有效
				cmdutil.CheckErr(fmt.Errorf("output must be one of '' or 'name': %v", outputFormat))
			}
			if !supportedOutputTypes.Has(outputFormat) {.//判断输出是否支持
				fmt.Fprintf(options.Out, "--output %v is not available in kubectl config get-contexts; resetting to default output format\n", outputFormat)
				cmd.Flags().Set("output", "")
			}
			cmdutil.CheckErr(options.Complete(cmd, args))//准备
			cmdutil.CheckErr(options.RunGetContexts())//运行
		},
	}

	cmd.Flags().Bool("no-headers", false, "When using the default or custom-column output format, don't print headers (default print headers).")//no-headers选项
	cmd.Flags().StringP("output", "o", "", "Output format. One of: name")//output选项
	return cmd
}
//准备
func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error {
	o.contextNames = args//设置contextNames
	o.nameOnly = false//设置nameOnly
	if cmdutil.GetFlagString(cmd, "output") == "name" {//如果输出格式是name,设置nameOnly为true
		o.nameOnly = true
	}
	o.showHeaders = true//设置showHeaders
	if cmdutil.GetFlagBool(cmd, "no-headers") || o.nameOnly {//如果no-headers或nameOnly为true,设置shouHeaders为false
		o.showHeaders = false
	}

	return nil
}
//运行
func (o GetContextsOptions) RunGetContexts() error {
	config, err := o.configAccess.GetStartingConfig()//加载config
	if err != nil {
		return err
	}

	out, found := o.Out.(*tabwriter.Writer)//把out转为tabwriter
	if !found {//转换失败
		out = printers.GetNewTabWriter(o.Out)//包装tabwriter
		defer out.Flush()
	}

	// Build a list of context names to print, and warn if any requested contexts are not found.
	// Do this before printing the headers so it doesn't look ugly.
	allErrs := []error{}
	toPrint := []string{}
	if len(o.contextNames) == 0 {//如果contextName为空
		for name := range config.Contexts {//append所有contexts name到toPrint
			toPrint = append(toPrint, name)
		}
	} else {
		for _, name := range o.contextNames {//遍历contextNames
			_, ok := config.Contexts[name]//判断context是否存在
			if ok {//如果存在append到toPrint
				toPrint = append(toPrint, name)
			} else {//不存在append错误
				allErrs = append(allErrs, fmt.Errorf("context %v not found", name))
			}
		}
	}
	if o.showHeaders {//如果showHeaders为true
		err = printContextHeaders(out, o.nameOnly)// 打印头
		if err != nil {
			allErrs = append(allErrs, err)
		}
	}

	sort.Strings(toPrint)//对context进行排序
	for _, name := range toPrint {//遍历toPrint
		err = printContext(name, config.Contexts[name], out, o.nameOnly, config.CurrentContext == name)//打印context
		if err != nil {
			allErrs = append(allErrs, err)
		}
	}

	return utilerrors.NewAggregate(allErrs)
}
//打印头
func printContextHeaders(out io.Writer, nameOnly bool) error {
	columnNames := []string{"CURRENT", "NAME", "CLUSTER", "AUTHINFO", "NAMESPACE"}
	if nameOnly {//如果nameOnly取第一个
		columnNames = columnNames[:1]
	}
	_, err := fmt.Fprintf(out, "%s\n", strings.Join(columnNames, "\t"))//打印头
	return err
}

//打印context
func printContext(name string, context *clientcmdapi.Context, w io.Writer, nameOnly, current bool) error {
	if nameOnly {//如果nameOnly打印name返回
		_, err := fmt.Fprintf(w, "%s\n", name)
		return err
	}
	prefix := " "
	if current {// 如果是当前context,打印*号
		prefix = "*"
	}
	_, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", prefix, name, context.Cluster, context.AuthInfo, context.Namespace)//打印context
	return err
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(kubectl源码分析之config get-contexts)