上一讲我们学习了k8s命令行接口kubectl在k8s源码的一级入口,这一讲我们根据具体的kubectl create创建资源对象命令来进一步学习这个接口的内在逻辑。

一.通过cobra程序构建cmd命令

Cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序。支持简单的子命令行模式,如 app server, app fetch等,支持嵌套子命令subcommand。

  1. 创建父命令,父命令中ValidateArgs函数对命令行输入的参数进行合规验证,RunCreate函数实现了创建资源对象的抽象逻辑
  2. 创建子命令,通过在cobra父命令中添加子命令的方式来进一步完成创建namespace、secret、service、deployment等资源对象cmd命令的构造
func NewCmdCreate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewCreateOptions(ioStreams)

    // 创建父命令
	cmd := &cobra.Command{
		Use: "create -f FILENAME",
		DisableFlagsInUseLine: true,
		Short:   i18n.T("Create a resource from a file or from stdin."),
		Long:    createLong,
		Example: createExample,
		Run: func(cmd *cobra.Command, args []string) {
			if cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames) {
				defaultRunFunc := cmdutil.DefaultSubCommandRun(ioStreams.ErrOut)
				defaultRunFunc(cmd, args)
				return
			}
			cmdutil.CheckErr(o.Complete(f, cmd))
			cmdutil.CheckErr(o.ValidateArgs(cmd, args))
			cmdutil.CheckErr(o.RunCreate(f, cmd))
		},
	}
    // bind flag structs
    // 绑定标志结构
	***
    ***
    //

	// create subcommands
    // 创建子命令
	cmd.AddCommand(NewCmdCreateNamespace(f, ioStreams))
	cmd.AddCommand(NewCmdCreateQuota(f, ioStreams))
	cmd.AddCommand(NewCmdCreateSecret(f, ioStreams))
	cmd.AddCommand(NewCmdCreateConfigMap(f, ioStreams))
	cmd.AddCommand(NewCmdCreateServiceAccount(f, ioStreams))
	cmd.AddCommand(NewCmdCreateService(f, ioStreams))
	cmd.AddCommand(NewCmdCreateDeployment(f, ioStreams))
	cmd.AddCommand(NewCmdCreateClusterRole(f, ioStreams))
	cmd.AddCommand(NewCmdCreateClusterRoleBinding(f, ioStreams))
	cmd.AddCommand(NewCmdCreateRole(f, ioStreams))
	cmd.AddCommand(NewCmdCreateRoleBinding(f, ioStreams))
	cmd.AddCommand(NewCmdCreatePodDisruptionBudget(f, ioStreams))
	cmd.AddCommand(NewCmdCreatePriorityClass(f, ioStreams))
	cmd.AddCommand(NewCmdCreateJob(f, ioStreams))
	return cmd
}

二.创建具体的资源对象(以deployment为例)

在NewCmdCreateDeployment方法中实现了对deployment资源对象的创建。其中DeploymentOpts结构体延用了CreateSubcommandOptions,该结构体中封装了deployment的名称(自定义),资源构建器StructuredGenerator,命名空间,映射器,动态客户端(实现create接口)等资源创建的细节。

func NewCmdCreateDeployment(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	options := &DeploymentOpts{
		CreateSubcommandOptions: NewCreateSubcommandOptions(ioStreams),
	}

	cmd := &cobra.Command{
		Use: "deployment NAME --image=image [--dry-run]",
		DisableFlagsInUseLine: true,
		Aliases:               []string{"deploy"},
		Short:                 i18n.T("Create a deployment with the specified name."),
		Long:                  deploymentLong,
		Example:               deploymentExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(options.Complete(f, cmd, args))
			cmdutil.CheckErr(options.Run())
		},
	}

	options.CreateSubcommandOptions.PrintFlags.AddFlags(cmd)

	cmdutil.AddApplyAnnotationFlags(cmd)
	cmdutil.AddValidateFlags(cmd)
	cmdutil.AddGeneratorFlags(cmd, "")
	cmd.Flags().StringSlice("image", []string{}, "Image name to run.")
	cmd.MarkFlagRequired("image")
	return cmd
}

其中,Run方法封装了deployment对象创建的具体实现方法

actualObject, err := o.DynamicClient.Resource(mapping.Resource).Namespace(o.Namespace).Create(asUnstructured)

上面这段代码通过识别要创建的资源对象版本,资源类型(resource),命名空间(namespace),自定义的资源名称创建具体的deployment资源对象。

Create的实现逻辑是通过向ApiServer发送Post请求创建资源对象,类似于

POST /apis/apps/v1/namespaces/{namespace}/deployments

func (o *CreateSubcommandOptions) Run() error {
	obj, err := o.StructuredGenerator.StructuredGenerate()
	if err != nil {
		return err
	}
	if !o.DryRun {
		// create subcommands have compiled knowledge of things they create, so type them directly
		// create子命令已经编译了他们创建的资源对象的信息,因此直接输入它们
		gvks, _, err := legacyscheme.Scheme.ObjectKinds(obj)
		if err != nil {
			return err
		}
		gvk := gvks[0]
		//构建封装了api版本映射器
		mapping, err := o.Mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
		if err != nil {
			return err
		}

		if err := kubectl.CreateOrUpdateAnnotation(o.CreateAnnotation, obj, cmdutil.InternalVersionJSONEncoder()); err != nil {
			return err
		}

		asUnstructured := &unstructured.Unstructured{}

		if err := legacyscheme.Scheme.Convert(obj, asUnstructured, nil); err != nil {
			return err
		}
		if mapping.Scope.Name() == meta.RESTScopeNameRoot {
			o.Namespace = ""
		}
		// 具体的deployment创建命令
		actualObject, err := o.DynamicClient.Resource(mapping.Resource).Namespace(o.Namespace).Create(asUnstructured)
		if err != nil {
			return err
		}

		// ensure we pass a versioned object to the printer
		obj = actualObject
	} else {
		if meta, err := meta.Accessor(obj); err == nil && o.EnforceNamespace {
			meta.SetNamespace(o.Namespace)
		}
	}

	return o.PrintObj(obj, o.Out)
}

 

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐