kubernetes源码分析controller-manager启动

本文详细分析了kube controller manager的启动过程,从cmd/kube-controller-manager目录的main函数开始,包括rand生成随机数、初始化command、日志设置和执行流程。重点关注在app目录下的ControllerManagerCommand创建,以及options的设定。深入到options.go中,探讨了manager管理的controller,如namespace、rc和deployment等。接着,文章详述了deployment controller的启动,分析了startDeploymentController的实现,包括创建eventBroadcaster、设置RateLimiter、创建DeploymentController对象,并配置事件回调和handler。最后,概述了工作循环及syncDeployment函数,展示了deployment事件的处理优先级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

kube controller manager 代码分析

1.目录: cmd/kube-controller-manager

在这里插入图片描述

2.main函数定义在cmd/kube-controller-manager/controller-manager.go

func main() {
	rand.Seed(time.Now().UnixNano())

	command := app.NewControllerManagerCommand()

	// TODO: once we switch everything over to Cobra commands, we can go back to calling
	// utilflag.InitFlags() (by removing its pflag.Parse() call). For now, we have to set the
	// normalize func and add the go flag set by hand.
	// utilflag.InitFlags()
	logs.InitLogs()
	defer logs.FlushLogs()

	if err := command.Execute(); err != nil {
		os.Exit(1)
	}
}

步骤: rand 生成随机数 --> 初始化command --> init log --> execute

  1. NewControllerManagerCommand 定义在app目录下

    cmd/kube-controller-manager/app/controllermanager.go

    源码定义:

    func NewControllerManagerCommand() *cobra.Command {
    	s, err := options.NewKubeControllerManagerOptions()
    	if err != nil {
    		klog.Fatalf("unable to initialize command options: %v", err)
    	}
    
    	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 nil
    		},
    	}
    
    	fs := cmd.Flags()
    	namedFlagSets := s.Flags(KnownControllers(), ControllersDisabledByDefault.List())
    	verflag.AddFlags(namedFlagSets.FlagSet("global"))
    	globalflag.AddGlobalFlags(namedFlagSets.FlagSet("global"), cmd.Name())
    	registerLegacyGlobalFlags(namedFlagSets)
    	for _, f := range namedFlagSets.FlagSets {
    		fs.AddFlagSet(f)
    	}
    	usageFmt := "Usage:\n  %s\n"
    	cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
    	cmd.SetUsageFunc(func(cmd *cobra.Command) error {
    		fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())
    		cliflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)
    		return nil
    	})
    	cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
    		fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine())
    		cliflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)
    	})
    
    	return cmd
    }
    

    1).NewControllerManagerCommand 返回 cobra.Command对象

    2).

    cmd := &cobra.Command{
    		Use: "kube-controller-manager",
    		...
    		}
    

    定义command信息

    3). 定义options

    s, err := options.NewKubeControllerManagerOptions()
    

    4.NewKubeControllerManagerOptions定义在cmd/kube-controller-manager/app/options/options.go

    
    // KubeControllerManagerOptions is the main context object for the kube-controller manager.
    type KubeControllerManagerOptions struct {
    	Generic           *cmoptions.GenericControllerManagerConfigurationOptions
    	KubeCloudShared   *cpoptions.KubeCloudSharedOptions
    	ServiceController *cpoptions.ServiceControllerOptions
    
    	AttachDetachController           *AttachDetachControllerOptions
    	CSRSigningController             *CSRSigningControllerOptions
    	DaemonSetController              *DaemonSetControllerOptions
    	DeploymentController             *DeploymentControllerOptions
    	StatefulSetController            *StatefulSetControllerOptions
    	DeprecatedFlags                  *DeprecatedControllerOptions
    	EndpointController               *EndpointControllerOptions
    	EndpointSliceController          *EndpointSliceControllerOptions
    	EndpointSliceMirroringController *EndpointSliceMirroringControllerOptions
    	GarbageCollectorController       *GarbageCollectorControllerOptions
    	HPAController                    *HPAControllerOptions
    	JobController                    *JobControllerOptions
    	CronJobController                *CronJobControllerOptions
    	NamespaceController              *NamespaceControllerOptions
    	NodeIPAMController               *NodeIPAMControllerOptions
    	NodeLifecycleController          *NodeLifecycleControllerOptions
    	PersistentVolumeBinderController *PersistentVolumeBinderCo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值