// Run runs the CMServer. This should never exit.
func Run(s *options.CMServer) error {
// 1. 驗證CM配置
if err := s.Validate(KnownControllers(), ControllersDisabledByDefault.List()); err != nil {
return err
}
....
kubeClient, leaderElectionClient, kubeconfig, err := createClients(s)
if err != nil {
return err
}
go startHTTP(s)
recorder := createRecorder(kubeClient)
// 2. 創建controllers啟動邏輯。run是真正用來啟動controllers的函數
run := func(stop <-chan struct{}) {
rootClientBuilder := controller.SimpleControllerClientBuilder{
ClientConfig: kubeconfig,
}
var clientBuilder controller.ControllerClientBuilder
....
ctx, err := CreateControllerContext(s, rootClientBuilder, clientBuilder, stop)
....
// NewControllerInitializers返回所有待啟動的controllers,StartControllers則依次啟動
if err := StartControllers(ctx, saTokenControllerInitFunc, NewControllerInitializers()); err != nil {
glog.Fatalf( "error starting controllers: %v" , err)
}
ctx.InformerFactory.Start(ctx.Stop)
close(ctx.InformersStarted)
select {}
}
...
// 3. 選主,由leader執行run函數
leaderelection.RunOrDie(leaderelection.LeaderElectionConfig{
Lock: rl,
LeaseDuration: s.LeaderElection.LeaseDuration.Duration,
RenewDeadline: s.LeaderElection.RenewDeadline.Duration,
RetryPeriod: s.LeaderElection.RetryPeriod.Duration,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: run,
OnStoppedLeading: func() {
glog.Fatalf( "leaderelection lost" )
},
},
})
panic( "unreachable" )
}
|