欢迎关注我的公众号:

kubectl源码分析之set subject_初始化



————————————————------------------------------------------------

type SubjectOptions struct {//setsubject结构体
PrintFlags *genericclioptions.PrintFlags

resource.FilenameOptions

Infos []*resource.Info
Selector string
ContainerSelector string
Output string
All bool
DryRun bool
Local bool

Users []string
Groups []string
ServiceAccounts []string

namespace string

PrintObj printers.ResourcePrinterFunc

genericclioptions.IOStreams
}
func NewSubjectOptions(streams genericclioptions.IOStreams) *SubjectOptions {
return &SubjectOptions{//初始化结构体
PrintFlags: genericclioptions.NewPrintFlags("subjects updated").WithTypeSetter(scheme.Scheme),

IOStreams: streams,
}
}
//创建set subject命令
func NewCmdSubject(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewSubjectOptions(streams)//初始化结构体
cmd := &cobra.Command{//创建cobra命令
Use: "subject (-f FILENAME | TYPE NAME) [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]",
DisableFlagsInUseLine: true,
Short: i18n.T("Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding"),
Long: subjectLong,
Example: subjectExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))//准备
cmdutil.CheckErr(o.Validate())//校验
cmdutil.CheckErr(o.Run(addSubjects))//运行
},
}

o.PrintFlags.AddFlags(cmd)//设置打印选项

cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "the resource to update the subjects")//设置文件选项
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().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().BoolVar(&o.Local, "local", o.Local, "If true, set subject will NOT contact api-server but run locally.")//设置local选项
cmdutil.AddDryRunFlag(cmd)
cmd.Flags().StringArrayVar(&o.Users, "user", o.Users, "Usernames to bind to the role")//设置user选项
cmd.Flags().StringArrayVar(&o.Groups, "group", o.Groups, "Groups to bind to the role")//设置group选项
cmd.Flags().StringArrayVar(&o.ServiceAccounts, "serviceaccount", o.ServiceAccounts, "Service accounts to bind to the role")//设置serviceaccount选项
cmdutil.AddIncludeUninitializedFlag(cmd)
return cmd
}
//准备函数
func (o *SubjectOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
o.Output = cmdutil.GetFlagString(cmd, "output")//设置output
o.DryRun = cmdutil.GetDryRunFlag(cmd)//设置dryrun

if o.DryRun {
o.PrintFlags.Complete("%s (dry run)")
}
printer, err := o.PrintFlags.ToPrinter()//print flag转printer
if err != nil {
return err
}
o.PrintObj = printer.PrintObj//设置printObj函数

var enforceNamespace bool
o.namespace, enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()//获取namespace和enforcenamespace
if err != nil {
return err
}

builder := f.NewBuilder().
WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
LocalParam(o.Local).
ContinueOnError().
NamespaceParam(o.namespace).DefaultNamespace().
FilenameParam(enforceNamespace, &o.FilenameOptions).
Flatten()//构造info对象

if o.Local {
// if a --local flag was provided, and a resource was specified in the form
// <resource>/<name>, fail immediately as --local cannot query the api server
// for the specified resource.
if len(args) > 0 {
return resource.LocalResourceError
}
} else {
builder = builder.
LabelSelectorParam(o.Selector).
ResourceTypeOrNameArgs(o.All, args...).
Latest()
}

o.Infos, err = builder.Do().Infos()//设置info对象
if err != nil {
return err
}

return nil
}
//校验
func (o *SubjectOptions) Validate() error {
if o.All && len(o.Selector) > 0 {//all和selector不同同时存在
return fmt.Errorf("cannot set --all and --selector at the same time")
}
if len(o.Users) == 0 && len(o.Groups) == 0 && len(o.ServiceAccounts) == 0 {//必须设置至少一个主体
return fmt.Errorf("you must specify at least one value of user, group or serviceaccount")
}

for _, sa := range o.ServiceAccounts {//serviceaccount必须是namespace:name
tokens := strings.Split(sa, ":")
if len(tokens) != 2 || tokens[1] == "" {
return fmt.Errorf("serviceaccount must be <namespace>:<name>")
}

for _, info := range o.Infos {
_, ok := info.Object.(*rbacv1.ClusterRoleBinding)
if ok && tokens[0] == "" {
return fmt.Errorf("serviceaccount must be <namespace>:<name>, namespace must be specified")
}
}
}

return nil
}
//运行
func (o *SubjectOptions) Run(fn updateSubjects) error {
patches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {//计算patch
subjects := []rbacv1.Subject{}
for _, user := range sets.NewString(o.Users...).List() {//遍历users
subject := rbacv1.Subject{//创建user主体
Kind: rbacv1.UserKind,
APIGroup: rbacv1.GroupName,
Name: user,
}
subjects = append(subjects, subject)//追加user主体
}
for _, group := range sets.NewString(o.Groups...).List() {//遍历groups
subject := rbacv1.Subject{//创建group主体
Kind: rbacv1.GroupKind,
APIGroup: rbacv1.GroupName,
Name: group,
}
subjects = append(subjects, subject)//追加group主体
}
for _, sa := range sets.NewString(o.ServiceAccounts...).List() {//遍历serviceaccount
tokens := strings.Split(sa, ":")//用:分割
namespace := tokens[0]
name := tokens[1]
if len(namespace) == 0 {//如果namespace为空则用资源所在的namespace
namespace = o.namespace
}
subject := rbacv1.Subject{//创建serviceaccount主体
Kind: rbacv1.ServiceAccountKind,
Namespace: namespace,
Name: name,
}
subjects = append(subjects, subject)//追加主体
}

transformed, err := updateSubjectForObject(obj, subjects, fn)//更新对象主体
if transformed && err == nil {
// TODO: switch UpdatePodSpecForObject to work on v1.PodSpec
return runtime.Encode(scheme.DefaultJSONEncoder(), obj)//obj转json
}
return nil, err
})

allErrs := []error{}
for _, patch := range patches {//遍历patches
info := patch.Info
name := info.ObjectName()
if patch.Err != nil {//如果有错误继续
allErrs = append(allErrs, fmt.Errorf("error: %s %v\n", name, patch.Err))
continue
}

//no changes
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {//如果patch为空继续
allErrs = append(allErrs, fmt.Errorf("info: %s was not changed\n", name))
continue
}

if o.Local || o.DryRun {//local或干跑打印对象继续
if err := o.PrintObj(info.Object, o.Out); err != nil {
allErrs = append(allErrs, err)
}
continue
}

actual, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)//应用patch到服务器
if err != nil {
allErrs = append(allErrs, fmt.Errorf("failed to patch subjects to rolebinding: %v", err))
continue
}

if err := o.PrintObj(actual, o.Out); err != nil {//打印对象
allErrs = append(allErrs, err)
}
}
return utilerrors.NewAggregate(allErrs)
}
func updateSubjectForObject(obj runtime.Object, subjects []rbacv1.Subject, fn updateSubjects) (bool, error) {//更新subject
switch t := obj.(type) {
case *rbacv1.RoleBinding:
transformed, result := fn(t.Subjects, subjects)//执行fn函数
t.Subjects = result//设置对象subject
return transformed, nil
case *rbacv1.ClusterRoleBinding:
transformed, result := fn(t.Subjects, subjects)//执行fn函数
t.Subjects = result//设置对象subject
return transformed, nil
default:
return false, fmt.Errorf("setting subjects is only supported for RoleBinding/ClusterRoleBinding")
}
}

func addSubjects(existings []rbacv1.Subject, targets []rbacv1.Subject) (bool, []rbacv1.Subject) {
transformed := false
updated := existings
for _, item := range targets {//遍历要更新的subject
if !contain(existings, item) {//existings不包含要更新的则添加
updated = append(updated, item)
transformed = true
}
}
return transformed, updated
}

func contain(slice []rbacv1.Subject, item rbacv1.Subject) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
}