欢迎关注我的公众号:
目前刚开始写一个月,一共写了18篇原创文章,文章目录如下:
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 AutoscaleOptions struct {//autoscale结构体
FilenameOptions *resource.FilenameOptions
RecordFlags *genericclioptions.RecordFlags
Recorder genericclioptions.Recorder
PrintFlags *genericclioptions.PrintFlags
ToPrinter func(string) (printers.ResourcePrinter, error)
Name string
Generator string
Min int32
Max int32
CPUPercent int32
createAnnotation bool
args []string
enforceNamespace bool
namespace string
dryRun bool
builder *resource.Builder
generatorFunc func(string, *meta.RESTMapping) (generate.StructuredGenerator, error)
HPAClient autoscalingv1client.HorizontalPodAutoscalersGetter
scaleKindResolver scale.ScaleKindResolver
genericclioptions.IOStreams
}
func NewAutoscaleOptions(ioStreams genericclioptions.IOStreams) *AutoscaleOptions {
return &AutoscaleOptions{//初始化结构体
PrintFlags: genericclioptions.NewPrintFlags("autoscaled").WithTypeSetter(scheme.Scheme),
FilenameOptions: &resource.FilenameOptions{},
RecordFlags: genericclioptions.NewRecordFlags(),
Recorder: genericclioptions.NoopRecorder{},
IOStreams: ioStreams,
}
}
// 创建autoscale命令
func NewCmdAutoscale(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewAutoscaleOptions(ioStreams)//初始化结构体
validArgs := []string{"deployment", "replicaset", "replicationcontroller"}
cmd := &cobra.Command{//创建cobra命令
Use: "autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU]",
DisableFlagsInUseLine: true,
Short: i18n.T("Auto-scale a Deployment, ReplicaSet, or ReplicationController"),
Long: autoscaleLong,
Example: autoscaleExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))//准备
cmdutil.CheckErr(o.Validate())//校验
cmdutil.CheckErr(o.Run())//运行
},
ValidArgs: validArgs,//有效参数
}
// bind flag structs
o.RecordFlags.AddFlags(cmd)//record选项
o.PrintFlags.AddFlags(cmd)//打印选项
cmd.Flags().StringVar(&o.Generator, "generator", generateversioned.HorizontalPodAutoscalerV1GeneratorName, i18n.T("The name of the API generator to use. Currently there is only 1 generator."))//generator选项
cmd.Flags().Int32Var(&o.Min, "min", -1, "The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value.")//min选项
cmd.Flags().Int32Var(&o.Max, "max", -1, "The upper limit for the number of pods that can be set by the autoscaler. Required.")//max选项
cmd.MarkFlagRequired("max")//max是必须的
cmd.Flags().Int32Var(&o.CPUPercent, "cpu-percent", -1, fmt.Sprintf("The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used."))//cpu-percent选项
cmd.Flags().StringVar(&o.Name, "name", "", i18n.T("The name for the newly created object. If not specified, the name of the input resource will be used."))//hpa名称
cmdutil.AddDryRunFlag(cmd)//干跑选项
cmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, "identifying the resource to autoscale.")//文件选项
cmdutil.AddApplyAnnotationFlags(cmd)//save-config选项
return cmd
}
//准备方法
func (o *AutoscaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
var err error
o.dryRun = cmdutil.GetFlagBool(cmd, "dry-run")//设置干跑
o.createAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)//设置是否创建last-applied-configuration注解
o.builder = f.NewBuilder()//设置builder
discoveryClient, err := f.ToDiscoveryClient()//获取client
if err != nil {
return err
}
o.scaleKindResolver = scale.NewDiscoveryScaleKindResolver(discoveryClient)//设置scaleKindResolver
o.args = args//设置参数
o.RecordFlags.Complete(cmd)//record complete
o.Recorder, err = o.RecordFlags.ToRecorder()//record flag转recorder
if err != nil {
return err
}
kubeClient, err := f.KubernetesClientSet()//设置kubeClient
if err != nil {
return err
}
o.HPAClient = kubeClient.AutoscalingV1()//设置HPAclient
// get the generator
o.generatorFunc = func(name string, mapping *meta.RESTMapping) (generate.StructuredGenerator, error) {//判断genetator,生成generator对象
switch o.Generator {
case generateversioned.HorizontalPodAutoscalerV1GeneratorName:
return &generateversioned.HorizontalPodAutoscalerGeneratorV1{
Name: name,
MinReplicas: o.Min,
MaxReplicas: o.Max,
CPUPercent: o.CPUPercent,
ScaleRefName: name,
ScaleRefKind: mapping.GroupVersionKind.Kind,
ScaleRefAPIVersion: mapping.GroupVersionKind.GroupVersion().String(),
}, nil
default:
return nil, cmdutil.UsageErrorf(cmd, "Generator %s not supported. ", o.Generator)
}
}
o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()//设置namespace和enforceNamespace
if err != nil {
return err
}
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()
}
return nil
}
// Validate checks that the provided attach options are specified.
//校验函数
func (o *AutoscaleOptions) Validate() error {
if o.Max < 1 {//max不能小于1
return fmt.Errorf("--max=MAXPODS is required and must be at least 1, max: %d", o.Max)
}
if o.Max < o.Min {//max必须大于min
return fmt.Errorf("--max=MAXPODS must be larger or equal to --min=MINPODS, max: %d, min: %d", o.Max, o.Min)
}
return nil
}
//运行
func (o *AutoscaleOptions) Run() error {
r := o.builder.
Unstructured().
ContinueOnError().
NamespaceParam(o.namespace).DefaultNamespace().
FilenameParam(o.enforceNamespace, o.FilenameOptions).
ResourceTypeOrNameArgs(false, o.args...).
Flatten().
Do()//构造result对象
if err := r.Err(); err != nil {
return err
}
count := 0
err := r.Visit(func(info *resource.Info, err error) error {//visit result对象
if err != nil {
return err
}
mapping := info.ResourceMapping()//获取info的mapping
gvr := mapping.GroupVersionKind.GroupVersion().WithResource(mapping.Resource.Resource)//获取groupverisonresource
if _, err := o.scaleKindResolver.ScaleForResource(gvr); err != nil {//判断资源是否可以scale
return fmt.Errorf("cannot autoscale a %v: %v", mapping.GroupVersionKind.Kind, err)
}
generator, err := o.generatorFunc(info.Name, mapping)//射程generator对象
if err != nil {
return err
}
// Generate new object
object, err := generator.StructuredGenerate()//用generator生成结构化对象
if err != nil {
return err
}
hpa, ok := object.(*autoscalingv1.HorizontalPodAutoscaler)//对象转hpa对象
if !ok {
return fmt.Errorf("generator made %T, not autoscalingv1.HorizontalPodAutoscaler", object)
}
if err := o.Recorder.Record(hpa); err != nil {//判断是否创建change-cause注解
klog.V(4).Infof("error recording current command: %v", err)
}
if o.dryRun {//如果是干跑
count++
printer, err := o.ToPrinter("created")//printflag转printer
if err != nil {
return err
}
return printer.PrintObj(hpa, o.Out)//打印结果
}
if err := util.CreateOrUpdateAnnotation(o.createAnnotation, hpa, scheme.DefaultJSONEncoder()); err != nil {//hpa对象是否创建last-applied-configuration注解
return err
}
actualHPA, err := o.HPAClient.HorizontalPodAutoscalers(o.namespace).Create(hpa)//创建hpa资源到服务端
if err != nil {
return err
}
count++
printer, err := o.ToPrinter("autoscaled")//printflag转printer
if err != nil {
return err
}
return printer.PrintObj(actualHPA, o.Out)//打印结果
})
if err != nil {
return err
}
if count == 0 {
return fmt.Errorf("no objects passed to autoscale")
}
return nil
}