kubectl源码分析之apply view-last-applied
  TEZNKK3IfmPf 2023年11月15日 24 0

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

type ViewLastAppliedOptions struct {//viewlastapplied结构体
  FilenameOptions              resource.FilenameOptions
  Selector                     string
  LastAppliedConfigurationList []string
  OutputFormat                 string
  All                          bool
  Factory                      cmdutil.Factory

  genericclioptions.IOStreams
}
func NewViewLastAppliedOptions(ioStreams genericclioptions.IOStreams) *ViewLastAppliedOptions {//初始化结构体
  return &ViewLastAppliedOptions{
    OutputFormat: "yaml",

    IOStreams: ioStreams,
  }
}
//创建viewLastApplied命令
func NewCmdApplyViewLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  options := NewViewLastAppliedOptions(ioStreams)//初始化结构体

  cmd := &cobra.Command{//创建cobra命令
    Use:                   "view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f FILENAME)",
    DisableFlagsInUseLine: true,
    Short:                 i18n.T("View latest last-applied-configuration annotations of a resource/object"),
    Long:                  applyViewLastAppliedLong,
    Example:               applyViewLastAppliedExample,
    Run: func(cmd *cobra.Command, args []string) {
      cmdutil.CheckErr(options.Complete(cmd, f, args))//准备
      cmdutil.CheckErr(options.Validate(cmd))//校验
      cmdutil.CheckErr(options.RunApplyViewLastApplied(cmd))//运行
    },
  }

  cmd.Flags().StringVarP(&options.OutputFormat, "output", "o", options.OutputFormat, "Output format. Must be one of yaml|json")//输出选项
  cmd.Flags().StringVarP(&options.Selector, "selector", "l", options.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")//selector选项
  cmd.Flags().BoolVar(&options.All, "all", options.All, "Select all resources in the namespace of the specified resource types")//all选项
  usage := "that contains the last-applied-configuration annotations"
  cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage)//文件选项

  return cmd
}
//准备
func (o *ViewLastAppliedOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error {
  cmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()//获取名称空间和enforce名称空间
  if err != nil {
    return err
  }

  r := f.NewBuilder().
    Unstructured().
    NamespaceParam(cmdNamespace).DefaultNamespace().
    FilenameParam(enforceNamespace, &o.FilenameOptions).
    ResourceTypeOrNameArgs(enforceNamespace, args...).
    SelectAllParam(o.All).
    LabelSelectorParam(o.Selector).
    Latest().
    Flatten().
    Do()//用builder构造result对象
  err = r.Err()
  if err != nil {
    return err
  }

  err = r.Visit(func(info *resource.Info, err error) error {visit result
    if err != nil {
      return err
    }

    configString, err := util.GetOriginalConfiguration(info.Object)//获取last-applied-configuration配置
    if err != nil {
      return err
    }
    if configString == nil {//配置为空返回错误
      return cmdutil.AddSourceToErr(fmt.Sprintf("no last-applied-configuration annotation found on resource: %s\n", info.Name), info.Source, err)
    }
    o.LastAppliedConfigurationList = append(o.LastAppliedConfigurationList, string(configString))//追加配置
    return nil
  })

  if err != nil {
    return err
  }

  return nil
}

// Validate checks ViewLastAppliedOptions for validity.
func (o *ViewLastAppliedOptions) Validate(cmd *cobra.Command) error {
  return nil
}
//运行
func (o *ViewLastAppliedOptions) RunApplyViewLastApplied(cmd *cobra.Command) error {
  for _, str := range o.LastAppliedConfigurationList {//遍历配置
    switch o.OutputFormat {
    case "json"://json格式输出
      jsonBuffer := &bytes.Buffer{}
      err := json.Indent(jsonBuffer, []byte(str), "", "  ")
      if err != nil {
        return err
      }
      fmt.Fprint(o.Out, string(jsonBuffer.Bytes()))
    case "yaml"://yaml格式输出
      yamlOutput, err := yaml.JSONToYAML([]byte(str))
      if err != nil {
        return err
      }
      fmt.Fprint(o.Out, string(yamlOutput))
    default:
      return cmdutil.UsageErrorf(
        cmd,
        "Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json",
        o.OutputFormat)
    }
  }

  return nil
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月17日   51   0   0 json
  TEZNKK3IfmPf   2024年04月26日   39   0   0 json
  TEZNKK3IfmPf   2024年04月26日   35   0   0 序列化json
  TEZNKK3IfmPf   2024年04月19日   50   0   0 javajson
  TEZNKK3IfmPf   2024年05月17日   50   0   0 jsonmysql
  TEZNKK3IfmPf   2024年03月30日   23   0   0 ios
TEZNKK3IfmPf