————————————————
type LabelOptions struct {//label结构体 // Filename options resource.FilenameOptions RecordFlags *genericclioptions.RecordFlags PrintFlags *genericclioptions.PrintFlags ToPrinter func(string) (printers.ResourcePrinter, error) // Common user flags overwrite bool list bool local bool dryrun bool all bool resourceVersion string selector string fieldSelector string outputFormat string // results of arg parsing resources []string newLabels map[string]string removeLabels []string Recorder genericclioptions.Recorder namespace string enforceNamespace bool builder *resource.Builder unstructuredClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error) // Common shared fields genericclioptions.IOStreams }
func NewLabelOptions(ioStreams genericclioptions.IOStreams) *LabelOptions { return &LabelOptions{//初始化结构体 RecordFlags: genericclioptions.NewRecordFlags(), Recorder: genericclioptions.NoopRecorder{}, PrintFlags: genericclioptions.NewPrintFlags("labeled").WithTypeSetter(scheme.Scheme), IOStreams: ioStreams, } }
//创建label命令 func NewCmdLabel(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { o := NewLabelOptions(ioStreams)//初始化结构体 cmd := &cobra.Command{//创建cobra命令 Use: "label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]", DisableFlagsInUseLine: true, Short: i18n.T("Update the labels on a resource"), Long: fmt.Sprintf(labelLong, validation.LabelValueMaxLength), Example: labelExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args))//准备 cmdutil.CheckErr(o.Validate())//校验 cmdutil.CheckErr(o.RunLabel())//运行 }, } o.RecordFlags.AddFlags(cmd)//record选项 o.PrintFlags.AddFlags(cmd)//打印选项 cmd.Flags().BoolVar(&o.overwrite, "overwrite", o.overwrite, "If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels.")//overwrite选项 cmd.Flags().BoolVar(&o.list, "list", o.list, "If true, display the labels for a given resource.")//list选项 cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, label will NOT contact api-server but run locally.")//local选项 cmd.Flags().StringVarP(&o.selector, "selector", "l", o.selector, "Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2).")//selector选项 cmd.Flags().StringVar(&o.fieldSelector, "field-selector", o.fieldSelector, "Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.")//fieldSelector选项 cmd.Flags().BoolVar(&o.all, "all", o.all, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")//all选项 cmd.Flags().StringVar(&o.resourceVersion, "resource-version", o.resourceVersion, i18n.T("If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource."))//resource-version选项 usage := "identifying the resource to update the labels" cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)//文件选项 cmdutil.AddDryRunFlag(cmd)//干跑选项 cmdutil.AddIncludeUninitializedFlag(cmd) return cmd }
//准备 func (o *LabelOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { var err error o.RecordFlags.Complete(cmd)//record complete o.Recorder, err = o.RecordFlags.ToRecorder()//record flag转recorder if err != nil { return err } o.outputFormat = cmdutil.GetFlagString(cmd, "output")//输出格式 o.dryrun = cmdutil.GetDryRunFlag(cmd)//设置干跑 o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {//printflag转printer函数 o.PrintFlags.NamePrintFlags.Operation = operation if o.dryrun { o.PrintFlags.Complete("%s (dry run)") } return o.PrintFlags.ToPrinter() } resources, labelArgs, err := cmdutil.GetResourcesAndPairs(args, "label")//抽取resrouce和label参数 if err != nil { return err } o.resources = resources o.newLabels, o.removeLabels, err = parseLabels(labelArgs)//解析lable参数 if o.list && len(o.outputFormat) > 0 {//不能同时指定list和output return fmt.Errorf("--list and --output may not be specified together") } o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()//设置namespace和EnforceNamespace if err != nil { return err } o.builder = f.NewBuilder()//设置builder o.unstructuredClientForMapping = f.UnstructuredClientForMapping//设置unstructuredClientForMapping return nil }
//校验 func (o *LabelOptions) Validate() error { if o.all && len(o.selector) > 0 {//all和selector不能同时指定 return fmt.Errorf("cannot set --all and --selector at the same time") } if o.all && len(o.fieldSelector) > 0 {//all和field-selector不能同时指定 return fmt.Errorf("cannot set --all and --field-selector at the same time") } if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {//资源和文件不能同时为空 return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>") } if len(o.newLabels) < 1 && len(o.removeLabels) < 1 && !o.list {//list和创建,删除label不能同时为空 return fmt.Errorf("at least one label update is required") } return nil }
func (o *LabelOptions) RunLabel() error { b := o.builder. Unstructured(). LocalParam(o.local). ContinueOnError(). NamespaceParam(o.namespace).DefaultNamespace(). FilenameParam(o.enforceNamespace, &o.FilenameOptions). Flatten()//用build构造result对象 if !o.local { b = b.LabelSelectorParam(o.selector). FieldSelectorParam(o.fieldSelector). ResourceTypeOrNameArgs(o.all, o.resources...). Latest() } one := false r := b.Do().IntoSingleItemImplied(&one) if err := r.Err(); err != nil { return err } // only apply resource version locking on a single resource if !one && len(o.resourceVersion) > 0 {//如果info不止一个,并指定了resource-version报错 return fmt.Errorf("--resource-version may only be used with a single resource") } // TODO: support bulk generic output a la Get return r.Visit(func(info *resource.Info, err error) error {// visit result if err != nil { return err } var outputObj runtime.Object var dataChangeMsg string obj := info.Object//获取info object oldData, err := json.Marshal(obj)//把obj转成json if err != nil { return err } if o.dryrun || o.local || o.list {// 如果是干跑,local,或list err = labelFunc(obj, o.overwrite, o.resourceVersion, o.newLabels, o.removeLabels)//给对象打标签 if err != nil { return err } newObj, err := json.Marshal(obj)//把打过标签的对象转成json if err != nil { return err } dataChangeMsg = updateDataChangeMsg(oldData, newObj)//判断是否有更改 outputObj = info.Object//设置outputObj } else { name, namespace := info.Name, info.Namespace//获取名称和名称空间 if err != nil { return err } accessor, err := meta.Accessor(obj)//访问对象 if err != nil { return err } for _, label := range o.removeLabels {// 遍历要删除的labels if _, ok := accessor.GetLabels()[label]; !ok {//如果要删除的label不存在则打印提示 fmt.Fprintf(o.Out, "label %q not found.\n", label) } } if err := labelFunc(obj, o.overwrite, o.resourceVersion, o.newLabels, o.removeLabels); err != nil {// 给对象打标签 return err } if err := o.Recorder.Record(obj); err != nil {//判断是否创建change-cause注解 klog.V(4).Infof("error recording current command: %v", err) } newObj, err := json.Marshal(obj)//吧对象转json if err != nil { return err } dataChangeMsg = updateDataChangeMsg(oldData, newObj)// 判断是否有更改 patchBytes, err := jsonpatch.CreateMergePatch(oldData, newObj)//创建patch createdPatch := err == nil if err != nil { klog.V(2).Infof("couldn't compute patch: %v", err) } mapping := info.ResourceMapping()// 获取mapping client, err := o.unstructuredClientForMapping(mapping)// 获取client if err != nil { return err } helper := resource.NewHelper(client, mapping)//构造helper if createdPatch {//应用patch到服务端 outputObj, err = helper.Patch(namespace, name, types.MergePatchType, patchBytes, nil) } else {// replace obj到服务端 outputObj, err = helper.Replace(namespace, name, false, obj) } if err != nil { return err } } if o.list {//如果指定了list accessor, err := meta.Accessor(outputObj)//访问要输出的对象 if err != nil { return err } indent := "" if !one {//如果是多个对象 indent = " " gvks, _, err := unstructuredscheme.NewUnstructuredObjectTyper().ObjectKinds(info.Object)//获取gvk if err != nil { return err } fmt.Fprintf(o.ErrOut, "Listing labels for %s.%s/%s:\n", gvks[0].Kind, gvks[0].Group, info.Name)//打印提示 } for k, v := range accessor.GetLabels() {//遍历labels,输出 fmt.Fprintf(o.Out, "%s%s=%s\n", indent, k, v) } return nil } printer, err := o.ToPrinter(dataChangeMsg)//printflag转printer if err != nil { return err } return printer.PrintObj(info.Object, o.Out)//打印对象 }) }
//给对象打标签 func labelFunc(obj runtime.Object, overwrite bool, resourceVersion string, labels map[string]string, remove []string) error { accessor, err := meta.Accessor(obj)//访问对象 if err != nil { return err } if !overwrite {// 如果没有指定overwrite if err := validateNoOverwrites(accessor, labels); err != nil {//判断标签是否冲突 return err } } objLabels := accessor.GetLabels()//获取对象labels if objLabels == nil { objLabels = make(map[string]string) } for key, value := range labels {//遍历要添加的标签,依次添加 objLabels[key] = value } for _, label := range remove {//遍历要删除的labels,依次删除 delete(objLabels, label) } accessor.SetLabels(objLabels)//设置对象的labels if len(resourceVersion) != 0 {// 如果resource-version不为空,设置resource-version accessor.SetResourceVersion(resourceVersion) } return nil }
func updateDataChangeMsg(oldObj []byte, newObj []byte) string {//判断是否有更新,返回提示字符串 msg := "not labeled" if !reflect.DeepEqual(oldObj, newObj) { msg = "labeled" } return msg } func validateNoOverwrites(accessor metav1.Object, labels map[string]string) error { allErrs := []error{} for key := range labels {//遍历要添加的labels if value, found := accessor.GetLabels()[key]; found {//如果label存在,则报错 allErrs = append(allErrs, fmt.Errorf("'%s' already has a value (%s), and --overwrite is false", key, value)) } } return utilerrors.NewAggregate(allErrs) } //解析labels func parseLabels(spec []string) (map[string]string, []string, error) { labels := map[string]string{} var remove []string for _, labelSpec := range spec {//遍历 if strings.Contains(labelSpec, "=") {//如果参数有=号 parts := strings.Split(labelSpec, "=")//用等号分割 if len(parts) != 2 {// 如果分割后不是两个,报错 return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec) } if errs := validation.IsValidLabelValue(parts[1]); len(errs) != 0 {//判断label是否有效字符串 return nil, nil, fmt.Errorf("invalid label value: %q: %s", labelSpec, strings.Join(errs, ";")) } labels[parts[0]] = parts[1]//把label放到map } else if strings.HasSuffix(labelSpec, "-") {//如果label末尾有- remove = append(remove, labelSpec[:len(labelSpec)-1])//添加label到remove slice } else {//否则返回错误 return nil, nil, fmt.Errorf("unknown label spec: %v", labelSpec) } } for _, removeLabel := range remove {//遍历remove slice if _, found := labels[removeLabel]; found {//如果label map里有removelabel则报错 return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command") } } return labels, remove, nil }