欢迎关注我的公众号:

kubectl源码分析之create cronjob_初始化

 

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

type CreateCronJobOptions struct {//create cronjob结构体
PrintFlags *genericclioptions.PrintFlags

PrintObj func(obj runtime.Object) error

Name string
Image string
Schedule string
Command []string
Restart string

Namespace string
Client batchv1beta1client.BatchV1beta1Interface
DryRun bool
Builder *resource.Builder
Cmd *cobra.Command

genericclioptions.IOStreams
}
func NewCreateCronJobOptions(ioStreams genericclioptions.IOStreams) *CreateCronJobOptions {
return &CreateCronJobOptions{//初始化结构体
PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme),
IOStreams: ioStreams,
}
}
//创建create cronjob 命令
func NewCmdCreateCronJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewCreateCronJobOptions(ioStreams)//初始化结构体
cmd := &cobra.Command{//创建cobra命令
Use: "cronjob NAME --image=image --schedule='0/5 * * * ?' -- [COMMAND] [args...]",
Aliases: []string{"cj"},
Short: cronjobLong,
Long: cronjobLong,
Example: cronjobExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))//准备运行
cmdutil.CheckErr(o.Validate())//校验
cmdutil.CheckErr(o.Run())//运行
},
}

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

cmdutil.AddApplyAnnotationFlags(cmd)//设置save-config选项
cmdutil.AddValidateFlags(cmd)//设置validate选项
cmdutil.AddDryRunFlag(cmd)//设置dry-run选项
cmd.Flags().StringVar(&o.Image, "image", o.Image, "Image name to run.")//设置image选项
cmd.Flags().StringVar(&o.Schedule, "schedule", o.Schedule, "A schedule in the Cron format the job should be run with.")//设置schedule选项
cmd.Flags().StringVar(&o.Restart, "restart", o.Restart, "job's restart policy. supported values: OnFailure, Never")//设置restart选项

return cmd
}
//准备方法
func (o *CreateCronJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)//获取名称
if err != nil {
return err
}
o.Name = name//设置名称
if len(args) > 1 {
o.Command = args[1:]//设置command
}
if len(o.Restart) == 0 {
o.Restart = "OnFailure"//如果restart为空,则restart为OnFailure
}

clientConfig, err := f.ToRESTConfig()//获取restconfig
if err != nil {
return err
}
o.Client, err = batchv1beta1client.NewForConfig(clientConfig)//设置client
if err != nil {
return err
}

o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()//设置namesapce
if err != nil {
return err
}
o.Builder = f.NewBuilder()//设置Builder
o.Cmd = cmd

o.DryRun = cmdutil.GetDryRunFlag(cmd)//设置dry-run
if o.DryRun {
o.PrintFlags.Complete("%s (dry run)")
}
printer, err := o.PrintFlags.ToPrinter()//print flag转printer
if err != nil {
return err
}
o.PrintObj = func(obj runtime.Object) error {//设置printObj函数
return printer.PrintObj(obj, o.Out)
}

return nil
}
//校验
func (o *CreateCronJobOptions) Validate() error {
if len(o.Image) == 0 {//image不能为空
return fmt.Errorf("--image must be specified")
}
if len(o.Schedule) == 0 {//schedule不能为空
return fmt.Errorf("--schedule must be specified")
}
return nil
}
//运行
func (o *CreateCronJobOptions) Run() error {
var cronjob *batchv1beta1.CronJob
cronjob = o.createCronJob()//创建Cronjob对象

if !o.DryRun {
var err error
cronjob, err = o.Client.CronJobs(o.Namespace).Create(cronjob)//通过client创建cronjob
if err != nil {
return fmt.Errorf("failed to create cronjob: %v", err)
}
}

return o.PrintObj(cronjob)//打印结果
}

func (o *CreateCronJobOptions) createCronJob() *batchv1beta1.CronJob {
return &batchv1beta1.CronJob{//创建cronjob对象并赋值属性
TypeMeta: metav1.TypeMeta{APIVersion: batchv1beta1.SchemeGroupVersion.String(), Kind: "CronJob"},
ObjectMeta: metav1.ObjectMeta{
Name: o.Name,
},
Spec: batchv1beta1.CronJobSpec{
Schedule: o.Schedule,
JobTemplate: batchv1beta1.JobTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: o.Name,
},
Spec: batchv1.JobSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: o.Name,
Image: o.Image,
Command: o.Command,
},
},
RestartPolicy: corev1.RestartPolicy(o.Restart),
},
},
},
},
},
}
}