本篇內(nèi)容主要講解“Kubernetes的Main函數(shù)怎么理解”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Kubernetes的Main函數(shù)怎么理解”吧!
10年的永安網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。成都全網(wǎng)營(yíng)銷的優(yōu)勢(shì)是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整永安建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。成都創(chuàng)新互聯(lián)公司從事“永安網(wǎng)站設(shè)計(jì)”,“永安網(wǎng)站推廣”以來,每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
讀過Kubernetes的源碼就會(huì)發(fā)現(xiàn),Kubernetes使用的是corba框架,所以各個(gè)組件的Main函數(shù)都大同小異,如下是kube-controller-manager的main函數(shù),
k8s.io/kubernetes/cmd/kube-controller-manager/controller-manager.go func main() { rand.Seed(time.Now().UTC().UnixNano()) command := app.NewControllerManagerCommand() //生成corba格式的Command,添加flag及初始化Command的各個(gè)函數(shù) // 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. pflag.CommandLine.SetNormalizeFunc(utilflag.WordSepNormalizeFunc) pflag.CommandLine.AddGoFlagSet(goflag.CommandLine) // utilflag.InitFlags() logs.InitLogs() defer logs.FlushLogs() if err := command.Execute(); err != nil { //執(zhí)行Command fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } }
首先調(diào)用options包的NewKubeControllerManagerOptions函數(shù)生成KubeControllerManagerOptions,其中給部分參數(shù)賦默認(rèn)值,參數(shù)的默認(rèn)值可查看代碼包:k8s.io/kubernetes/pkg/controller/apis/config/v1alpha1/defaults.go以及NewKubeControllerManagerOptions函數(shù)最后10行左右的代碼。
生成Kube-controller-manager的Command
生成controller-manager各個(gè)controller的參數(shù),并將它們添加到kube-controller-manager的Command的Flag中,controller的參數(shù)可查看k8s.io/kubernetes/cmd/kube-controller-manager/app/options庫和k8s.io/kubernetes/cmd/controller-manager/app/options庫中各個(gè)controller包中的AddFlags函數(shù)
設(shè)置Kube-controller-manager的usage和help函數(shù)
k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go:77func NewControllerManagerCommand() *cobra.Command { s, err := options.NewKubeControllerManagerOptions() //生成KubeControllerManagerOptions結(jié)構(gòu)體 if err != nil { glog.Fatalf("unable to initialize command options: %v", err) } cmd := &cobra.Command{ //生成kube-controller-manager的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.`, Run: func(cmd *cobra.Command, args []string) { verflag.PrintAndExitIfRequested() utilflag.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) } }, } fs := cmd.Flags() namedFlagSets := s.Flags(KnownControllers(), ControllersDisabledByDefault.List()) //生成controller-manager各個(gè)controller的參數(shù) for _, f := range namedFlagSets.FlagSets { //將各個(gè)controller的參數(shù)添加到Command的flag中 fs.AddFlagSet(f) } usageFmt := "Usage:\n %s\n" cols, _, _ := apiserverflag.TerminalSize(cmd.OutOrStdout()) cmd.SetUsageFunc(func(cmd *cobra.Command) error { //設(shè)置Kube-controller-manager的Usage函數(shù) fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine()) apiserverflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols) return nil }) cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) { //設(shè)置Kube-controller-manager的help函數(shù) fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine()) apiserverflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols) }) return cmd }
生成command以后,就執(zhí)行command.Execute函數(shù),即執(zhí)行上一步NewKubeControllerManagerOptions函數(shù)中給command定義的Run函數(shù)。注:corba的command.Execute方法是有很多檢查的,會(huì)有parent command及command本身也會(huì)有很多函數(shù)(i.e PreRun,PostRun),有興趣的可以閱讀github.com/spf13/cobra項(xiàng)目,因?yàn)閗ube-controller-manager只定義了Run函數(shù),所以這里就直接看Run函數(shù)。
檢查是否帶了--version參數(shù),如果有,則打印Kubernetes的version并退出kube-controller-manager程序
將所有的參數(shù)及參數(shù)的value打印到日志
option的Config方法對(duì)所有的controller做validation,并根據(jù)options的Master,Kubeconfig,ContentType,Qps,Burst參數(shù)生成controller manager config objective
執(zhí)行本包中的Run函數(shù)
k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go:93Run: func(cmd *cobra.Command, args []string) { verflag.PrintAndExitIfRequested() //檢查是否帶了--version參數(shù),如果有,則打印Kubernetes的version并退出程序 utilflag.PrintFlags(cmd.Flags()) //將所有的參數(shù)及參數(shù)的value打印到日志 //Config方法對(duì)所有的controller做validation,并根據(jù)options的Master,Kubeconfig,ContentType,Qps,Burst參數(shù)生成controller manager config objective 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 { //執(zhí)行本包中的Run函數(shù) fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } }
啟動(dòng)http服務(wù),聽health接口,以及給prometheus提供metrics接口
定義run函數(shù),主要是定義client,以及啟動(dòng)所有的controller,controller的啟動(dòng)函數(shù)都在k8s.io/kubernetes/cmd/kube-controller-manager/app/core.go中
如果沒有啟用leader-elect,則直接執(zhí)行上面的run函數(shù)
如果啟用了leader-elect,在選舉以后,再執(zhí)行上面看的run函數(shù)
k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go:141func Run(c *config.CompletedConfig, stopCh <-chan struct{}) error { // To help debugging, immediately log version glog.Infof("Version: %+v", version.Get()) if cfgz, err := configz.New("componentconfig"); err == nil { cfgz.Set(c.ComponentConfig) } else { glog.Errorf("unable to register configz: %c", err) } // 啟動(dòng)http服務(wù),提供health接口,以及給prometheus提供metrics接口 // Start the controller manager HTTP server // unsecuredMux is the handler for these controller *after* authn/authz filters have been applied var unsecuredMux *mux.PathRecorderMux if c.SecureServing != nil { unsecuredMux = genericcontrollermanager.NewBaseHandler(&c.ComponentConfig.Generic.Debugging) handler := genericcontrollermanager.BuildHandlerChain(unsecuredMux, &c.Authorization, &c.Authentication) if err := c.SecureServing.Serve(handler, 0, stopCh); err != nil { return err } } if c.InsecureServing != nil { unsecuredMux = genericcontrollermanager.NewBaseHandler(&c.ComponentConfig.Generic.Debugging) insecureSuperuserAuthn := server.AuthenticationInfo{Authenticator: &server.InsecureSuperuser{}} handler := genericcontrollermanager.BuildHandlerChain(unsecuredMux, nil, &insecureSuperuserAuthn) if err := c.InsecureServing.Serve(handler, 0, stopCh); err != nil { return err } } //定義run函數(shù) run := func(ctx context.Context) { rootClientBuilder := controller.SimpleControllerClientBuilder{ //定義rootrootClientBuilder ClientConfig: c.Kubeconfig, } var clientBuilder controller.ControllerClientBuilder //如果設(shè)置了UseServiceAccountCredentials,設(shè)clientBuilder為SAControllerClientBuilder(帶授權(quán)),否則為普通的rootClientBuilder if c.ComponentConfig.KubeCloudShared.UseServiceAccountCredentials { if len(c.ComponentConfig.SAController.ServiceAccountKeyFile) == 0 { // It'c possible another controller process is creating the tokens for us. // If one isn't, we'll timeout and exit when our client builder is unable to create the tokens. glog.Warningf("--use-service-account-credentials was specified without providing a --service-account-private-key-file") } clientBuilder = controller.SAControllerClientBuilder{ ClientConfig: restclient.AnonymousClientConfig(c.Kubeconfig), CoreClient: c.Client.CoreV1(), AuthenticationClient: c.Client.AuthenticationV1(), Namespace: "kube-system", } } else { clientBuilder = rootClientBuilder } controllerContext, err := CreateControllerContext(c, rootClientBuilder, clientBuilder, ctx.Done()) if err != nil { glog.Fatalf("error building controller context: %v", err) } //定義saTokenControllerInitFunc saTokenControllerInitFunc := serviceAccountTokenControllerStarter{rootClientBuilder: rootClientBuilder}.startServiceAccountTokenController //啟動(dòng)所有的controller,NewControllerInitializers函數(shù)中有所有的controller if err := StartControllers(controllerContext, saTokenControllerInitFunc, NewControllerInitializers(controllerContext.LoopMode), unsecuredMux); err != nil { glog.Fatalf("error starting controllers: %v", err) } controllerContext.InformerFactory.Start(controllerContext.Stop) close(controllerContext.InformersStarted) select {} } if !c.ComponentConfig.Generic.LeaderElection.LeaderElect { //如果沒有啟用leader-elect,則直接執(zhí)行上面的run函數(shù) run(context.TODO()) panic("unreachable") } id, err := os.Hostname() if err != nil { return err } //如果啟用了leader-elect,在選舉以后,再執(zhí)行上面看的run函數(shù) // add a uniquifier so that two processes on the same host don't accidentally both become active id = id + "_" + string(uuid.NewUUID()) rl, err := resourcelock.New(c.ComponentConfig.Generic.LeaderElection.ResourceLock, "kube-system", "kube-controller-manager", c.LeaderElectionClient.CoreV1(), resourcelock.ResourceLockConfig{ Identity: id, EventRecorder: c.EventRecorder, }) if err != nil { glog.Fatalf("error creating lock: %v", err) } leaderelection.RunOrDie(context.TODO(), leaderelection.LeaderElectionConfig{ Lock: rl, LeaseDuration: c.ComponentConfig.Generic.LeaderElection.LeaseDuration.Duration, RenewDeadline: c.ComponentConfig.Generic.LeaderElection.RenewDeadline.Duration, RetryPeriod: c.ComponentConfig.Generic.LeaderElection.RetryPeriod.Duration, Callbacks: leaderelection.LeaderCallbacks{ OnStartedLeading: run, OnStoppedLeading: func() { glog.Fatalf("leaderelection lost") }, }, }) panic("unreachable") }
到此,相信大家對(duì)“Kubernetes的Main函數(shù)怎么理解”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
網(wǎng)站名稱:Kubernetes的Main函數(shù)怎么理解
URL標(biāo)題:http://jinyejixie.com/article6/iisjig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、網(wǎng)站維護(hù)、虛擬主機(jī)、網(wǎng)站收錄、用戶體驗(yàn)、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)