k8s Source Analysis-----Kubelet co-process analysis

Source: Internet
Author: User
Tags auth create directory garbage collection reflector k8s
(1) garbage cans collection ProcessIn the Kubeletconfig Createandinitkubelet function, call K. Startgarbagecollection () Start
k8s.io\kubernetes\cmd\kubelet\app\server.go:982

Starts garbage collection threads.
Func (KL *kubelet) startgarbagecollection () {go wait
       . Until (func () {
              if err: = Kl.containerGC.GarbageCollect (Kl.sourcesReady.AllReady ()); Err!= nil {glog
                     . Errorf ("Container garbage collection failed:%v", err)
              }
       }, Containergcperiod, wait. neverstop) go wait

       . Until (func () {
              if err: = Kl.imageManager.GarbageCollect (); Err!= nil {
                     glog. Errorf ("Image garbage collection failed:%v", err)
              }
       }, Imagegcperiod, wait. Neverstop)
}

(2) Four initializemodule are started in the function

Func (KL *kubelet) Run call Initializemodules-"Imagemanager.start

K8s.io/kubernetes/pkg/kubelet. (*realimagemanager). Start
k8s.io/kubernetes/pkg/kubelet/cm. (*containermanagerimpl). Start
K8s.io/kubernetes/pkg/kubelet. (*realoomwatcher). Start
K8s.io/kubernetes/pkg/kubelet/server/stats. (*fsresourceanalyzer). Start

Initializemodules'll initialize internal modules that does not require the container runtime to is up.
Note This modules here must not depend on modules which are not initialized here.
       Func (KL *kubelet) Initializemodules () error {//step 1:promethues metrics. Metrics.
       Register (Kl.runtimecache)//Step 2:setup filesystem directories. If err: = Kl.setupdatadirs (); Err!= nil {return err}//step 3:if the container logs directory does not exist, create I T. If _, Err: = OS. Stat (Containerlogsdir); Err!= Nil {if err: = Kl.os.MkdirAll (Containerlogsdir, 0755); Err!= nil {glog. Errorf ("Failed to create directory%q:%v", Containerlogsdir, Err)}//step 4:start the I
       Mage Manager. If err: = Kl.imageManager.Start (); Err!= Nil {return FMT.
     Errorf ("Failed to start Imagemanager, images may isn't be garbage collected:%v", err)  //Step 5:start container manager. If err: = Kl.containerManager.Start (); Err!= Nil {return FMT.
       Errorf ("Failed to start Containermanager%v", err)}//step 6:start out of memory watcher. If err: = Kl.oomWatcher.Start (KL.NODEREF); Err!= Nil {return FMT. Errorf ("Failed to start OOM watcher%v", err)}//Step 7:start Resource Analyzer Kl.resourceanalyz Er. Start () return nil}

(3) Kubelet initiated in the Run function
Kubelet the Run function to start most of the coprocessor
Run starts the Kubelet reacting to config updates func (KL *kubelet) run updates <-chan. Podupdate) {if Kl.logserver = = Nil {kl.logserver = http. Stripprefix ("/logs/", http. Fileserver (http. Dir ("/var/log/"))} if kl.kubeclient = = Nil {glog.
       Warning ("No API server defined-no node status update would be sent.") If err: = Kl.initializemodules (); Err!= Nil {kl.recorder.Eventf (Kl.noderef, API. Eventtypewarning, Kubecontainer. Kubeletsetupfailed, Err. Error ()) Glog. Error (Err) Kl.runtimeState.setInitError (ERR)}//Start volume manager Go kl.volumeman Ager. Run (wait. Neverstop) If kl.kubeclient!= nil {//Start syncing node status immediately, this could set up thing
              s the runtime needs to run. Go wait. Until (Kl.syncnodestatus, Kl.nodestatusupdatefrequency, wait.) Neverstop)} go wait. Until (Kl.syncnetworkstatUS, 30*time. Second, wait. neverstop) Go wait. Until (Kl.updateruntimeup, 5*time. Second, wait. Neverstop)//Start a goroutine responsible for killing pods (this are not properly//handled by pod Worke
       RS). Go wait. Until (Kl.podkiller, 1*time. Second, wait.
       Neverstop)//Start component Sync loops. Kl.statusManager.Start () Kl.probeManager.Start () Kl.evictionManager.Start () (Kl.getactivepods, Evictionmonitori
       Ngperiod)//Start The Pod Lifecycle event generator. Kl.pleg.Start () Kl.syncloop (Updates, KL)}

(4) The server.go of the start Healthz in the run function of the
The code location is: k8s.io\kubernetes\cmd\kubelet\app\server.go:396
In the run function of Server.go
If S.healthzport > 0 {
       healthz. Defaulthealthz () Go wait
       . Until (func () {
              err: = http. Listenandserve (NET. Joinhostport (S.healthzbindaddress, StrConv. itoa (int (s.healthzport))), nil)
              If err!= nil {
                     glog. Errorf ("Starting Health Server failed:%v", err)
              }
       }, 5*time. Second, wait. Neverstop)
}

(5) The flush of the log
In main function: Util. Initlogs ()

Initlogs Initializes logs the way we want for kubernetes.
Func initlogs () {
       log. Setoutput (glogwriter{})
       log. SetFlags (0)
       //The default Glog flush interval is seconds, which is frighteningly long.
       Go wait. Until (Glog. Flush, *logflushfreq, wait. Neverstop)
}

(6) sourcefile Ctrip
Func newsourcefile (Path string, nodename string, period time. Duration, Updates chan<-interface{}) {
       config: = &sourcefile{
              path:     path,
              nodename:nodename ,
              updates:  updates,
       }
       glog. V (1). Infof ("Watching path%q", path) go wait
       . Until (Config.run, period, wait.) Neverstop)
}


Call chain is run-> runkubelet-> createandinitkubelet->makepodsourceconfig->newsourcefile (7) sourceURL co-process
Func newsourceurl (URL string, header http. Header, nodename string, period time. Duration, Updates chan<-interface{}) {
       config: = &sourceurl{
              url:      URL,
              header:   header,
              Nodename:nodename,
              updates:  updates,
              data:     nil,
              //Timing out requests leads to retries. This was only used to
              //Read the "manifest URL passed to Kubelet.
              Client: &http. Client{timeout:10 * time. Second},
       }
       glog. V (1). Infof ("Watching URL%s", url) go wait
       . Until (Config.run, period, wait.) Neverstop)
}


Call chain is run-> runkubelet-> createandinitkubelet->makepodsourceconfig->newsourceurl
(8) Apiservice Watch co-process
Newsourceapiserver creates a config source that watches and pulls from the apiserver.
Func Newsourceapiserver (c *clientset. Clientset, nodename string, updates chan<-interface{}) {
       LW: = cache. Newlistwatchfromclient (c.coreclient, "pods", API. Namespaceall, fields. Onetermequalselector (API. Podhostfield, nodename))
       NEWSOURCEAPISERVERFROMLW (LW, updates)
}

NEWSOURCEAPISERVERFROMLW holds creates a config source that watches and pulls from the apiserver.
Func NEWSOURCEAPISERVERFROMLW (LW cache. Listerwatcher, Updates chan<-interface{}) {
       send: = Func (Objs []interface{}) {
              var pods []*api. Pod
              for _, O: = Range Objs {
                     pods = append (pods, O. *api. Pod))
              }
              updates <-kubetypes. Podupdate{pods:pods, Op:kubetypes. SET, Source:kubetypes. Apiserversource}
       cache. Newreflector (LW, &api. pod{}, Cache. Newundeltastore (send, Cache. Metanamespacekeyfunc), 0). Run ()
}

Run starts a watch and handles watch events. Would restart the watch if it is closed.
Run starts a goroutine and returns immediately.
Func (R *reflector) Run () {
       glog. V (3). Infof ("Starting reflector%v (%s) from%s", R.expectedtype, R.resyncperiod, r.name) go
       . Until (func () {
              if err: = R.listandwatch (wait. Neverstop); Err!= Nil {
                     utilruntime. HandleError (Err)
              }
       }, R.period, wait. Neverstop)
}


Call chain is run-> runkubelet-> createandinitkubelet->makepodsourceconfig->newsourceurl


(9) Start the Kubelet Server co-processThe coprocessor starts after the start of the run function's coprocessor is complete
Func Startkubelet (k kubeletbootstrap, Podcfg *config. Podconfig, KC *kubeletconfig) {
       //start the Kubelet go wait
       . Until (func () {K.run (Podcfg.updates ())}, 0, wait. Neverstop)

       //Start the Kubelet server
       if KC. Enableserver {go wait
              . Until (func () {
                     k.listenandserve (KC). Address, KC. Port, KC. Tlsoptions, KC. Auth, KC. enabledebugginghandlers)
              }, 0, wait. neverstop)
       }
       if KC. Readonlyport > 0 {go wait
              . Until (func () {
                     k.listenandservereadonly (KC). Address, KC. Readonlyport)
              }, 0, wait. neverstop)
       }
}

Listenandserve runs the Kubelet HTTP server.
Func (KL *kubelet) Listenandserve (address net. IP, port UINT, tlsoptions *server. Tlsoptions, auth server. Authinterface, enabledebugginghandlers bool) {
       server. Listenandservekubeletserver (KL, Kl.resourceanalyzer, address, Port, Tlsoptions, auth, Enabledebugginghandlers, Kl.containerruntime)
}


Listenandservekubeletserver Initializes a server to respond to HTTP network requests on the Kubelet. Func Listenandservekubeletserver (host Hostinterface, Resourceanalyzer stats. Resourceanalyzer, address net.
       IP, port UINT, tlsoptions *tlsoptions, auth authinterface, enabledebugginghandlers bool, Runtime Kubecontainer. Runtime) {Glog. Infof ("Starting to listen on%s:%d", address, port) Handler: = NewServer (host, Resourceanalyzer, Auth, Enabledebugg Inghandlers, runtime) s: = &http. server{addr:net. Joinhostport (address. String (), StrConv.
       Formatuint (UInt64 (port)), Handler: &handler, maxheaderbytes:1 << 20, } if Tlsoptions!= nil {s.tlsconfig = Tlsoptions.config glog. Fatal (S.listenandservetls (Tlsoptions.certfile, tlsoptions.keyfile))} else {Glog. Fatal (S.listenandserve ())
       }
} 




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.