cobra 是go语言创建命令很好的一个工具, cobra 是由 spf13 写的 golang 库,
地址: https://github.com/spf13/cobra
k8s cmd是基于cobra的
例如 cmd/kube-controller-manager/app/controllermanager.go NewControllerManagerCommand定义如下:
cmd := &cobra.Command{
Use: "kube-controller-manager",
Long: `The Kubernetes controller manager is a daemon that embeds
the core control loops shipped with Kubernetes. In applications of robotics and
automation, a control loop is a non-terminating loop that regulates the state of
the system. In Kubernetes, a controller is a control loop that watches the shared
state of the cluster through the apiserver and makes changes attempting to move the
current state towards the desired state. Examples of controllers that ship with
Kubernetes today are the replication controller, endpoints controller, namespace
controller, and serviceaccounts controller.`,
PersistentPreRunE: func(*cobra.Command, []string) error {
// silence client-go warnings.
// kube-controller-manager generically watches APIs (including deprecated ones),
// and CI ensures it works properly against matching kube-apiserver versions.
restclient.SetDefaultWarningHandler(restclient.NoWarnings{})
return nil
},
Run: func(cmd *cobra.Command, args []string) {
verflag.PrintAndExitIfRequested()
cliflag.PrintFlags(cmd.Flags())
c, err := s.Config(KnownControllers(), ControllersDisabledByDefault.List())
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
if err := Run(c.Complete(), wait.NeverStop); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
},
Args: func(cmd *cobra.Command, args []string) error {
for _, arg := range args {
if len(arg) > 0 {
return fmt.Errorf("%q does not take any arguments, got %q", cmd.CommandPath(), args)
}
}
return
深入理解Kubernetes:cobra命令库解析

本文探讨了Kubernetes项目中广泛使用的 Cobra 命令行库,该库由 spf13 创建,用于Go语言应用。通过分析 `kube-controller-manager` 的 `NewControllerManagerCommand` 示例,揭示了如何定义命令、参数及其执行流程。Cobra 提供了添加子命令的功能,是构建复杂命令行工具的强大工具。
最低0.47元/天 解锁文章
890

被折叠的 条评论
为什么被折叠?



