阿里云服务器搭建网站央视网新闻
欢迎关注我的公众号:
目前刚开始写一个月,一共写了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完全手册
加qq群,请联系:
————————————————------------------------------------------------
type SubjectOptions struct {//setsubject结构体PrintFlags *genericclioptions.PrintFlagsresource.FilenameOptionsInfos []*resource.InfoSelector stringContainerSelector stringOutput stringAll boolDryRun boolLocal boolUsers []stringGroups []stringServiceAccounts []stringnamespace stringPrintObj printers.ResourcePrinterFuncgenericclioptions.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")//设置outputo.DryRun = cmdutil.GetDryRunFlag(cmd)//设置dryrunif o.DryRun {o.PrintFlags.Complete("%s (dry run)")}printer, err := o.PrintFlags.ToPrinter()//print flag转printerif err != nil {return err}o.PrintObj = printer.PrintObj//设置printObj函数var enforceNamespace boolo.namespace, enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()//获取namespace和enforcenamespaceif 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:nametokens := 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) {//计算patchsubjects := []rbacv1.Subject{}for _, user := range sets.NewString(o.Users...).List() {//遍历userssubject := rbacv1.Subject{//创建user主体Kind: rbacv1.UserKind,APIGroup: rbacv1.GroupName,Name: user,}subjects = append(subjects, subject)//追加user主体}for _, group := range sets.NewString(o.Groups...).List() {//遍历groupssubject := rbacv1.Subject{//创建group主体Kind: rbacv1.GroupKind,APIGroup: rbacv1.GroupName,Name: group,}subjects = append(subjects, subject)//追加group主体}for _, sa := range sets.NewString(o.ServiceAccounts...).List() {//遍历serviceaccounttokens := strings.Split(sa, ":")//用:分割namespace := tokens[0]name := tokens[1]if len(namespace) == 0 {//如果namespace为空则用资源所在的namespacenamespace = 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.PodSpecreturn runtime.Encode(scheme.DefaultJSONEncoder(), obj)//obj转json}return nil, err})allErrs := []error{}for _, patch := range patches {//遍历patchesinfo := patch.Infoname := info.ObjectName()if patch.Err != nil {//如果有错误继续allErrs = append(allErrs, fmt.Errorf("error: %s %v\n", name, patch.Err))continue}//no changesif 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) {//更新subjectswitch t := obj.(type) {case *rbacv1.RoleBinding:transformed, result := fn(t.Subjects, subjects)//执行fn函数t.Subjects = result//设置对象subjectreturn transformed, nilcase *rbacv1.ClusterRoleBinding:transformed, result := fn(t.Subjects, subjects)//执行fn函数t.Subjects = result//设置对象subjectreturn transformed, nildefault:return false, fmt.Errorf("setting subjects is only supported for RoleBinding/ClusterRoleBinding")}
}func addSubjects(existings []rbacv1.Subject, targets []rbacv1.Subject) (bool, []rbacv1.Subject) {transformed := falseupdated := existingsfor _, item := range targets {//遍历要更新的subjectif !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
}