kubectl源码分析之config get-contexts

 欢迎关注我的公众号:

 目前刚开始写一个月,一共写了18篇原创文章,文章目录如下:

istio多集群探秘,部署了50次多集群后我得出的结论

istio多集群链路追踪,附实操视频

istio防故障利器,你知道几个,istio新手不要读,太难!

istio业务权限控制,原来可以这么玩

istio实现非侵入压缩,微服务之间如何实现压缩

不懂envoyfilter也敢说精通istio系列-http-rbac-不要只会用AuthorizationPolicy配置权限

不懂envoyfilter也敢说精通istio系列-02-http-corsFilter-不要只会vs

不懂envoyfilter也敢说精通istio系列-03-http-csrf filter-再也不用再代码里写csrf逻辑了

不懂envoyfilter也敢说精通istio系列http-jwt_authn-不要只会RequestAuthorization

不懂envoyfilter也敢说精通istio系列-05-fault-filter-故障注入不止是vs

不懂envoyfilter也敢说精通istio系列-06-http-match-配置路由不只是vs

不懂envoyfilter也敢说精通istio系列-07-负载均衡配置不止是dr

不懂envoyfilter也敢说精通istio系列-08-连接池和断路器

不懂envoyfilter也敢说精通istio系列-09-http-route filter

不懂envoyfilter也敢说精通istio系列-network filter-redis proxy

不懂envoyfilter也敢说精通istio系列-network filter-HttpConnectionManager

不懂envoyfilter也敢说精通istio系列-ratelimit-istio ratelimit完全手册

 

————————————————

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hxpjava1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值