"Kubernetes/k8s Source Analysis" Kubelet Source analysis-start operation and information processing

Source: Internet
Author: User
Tags auth k8s cadvisor
Kubelet runs a kubelet service process on each node, listens to port 10250 by default, receives and executes commands from master, and manages containers in pod and pod. Each kubelet process registers the node's own information on the API server, periodically reports the resource usage of the node to the master node, and monitors the nodes and container resources through Cadvisor. Node management node management is mainly node self-registration and Node State Update: Kubelet can determine whether to register itself with API server by setting the startup parameter--register-node, if Kubelet does not select from registration mode, You need the user to configure node resource information, and you need to tell the location of the API server on the Kubelet cluster, kubelet to register the node information through API server at startup, and periodically send node new messages to API server, API When the server receives a new message, it writes the information to ETCD--api-server//Set up the API server location--kubeconfig//Set the certificate to access the API server--cloud-provider// How to read the relevant metadata from the cloud service--node-status-update-frequency//reporting time to API server, default 10s
Container Health Check Kubelet periodically invokes the Livenessprobe probe in the container to diagnose the health of the container. Livenessprobe contains the following three implementations: execaction: Executes a command inside the container, indicating that the container is healthy if the command's exit status code is 0; Tcpsocketaction: Performs a TCP check through the container's IP address and port number. If the port can be accessed, the container is healthy; Httpgetaction: Calls the HTTP GET method through the container's IP address and port number and path, if the response state code is greater than or equal to 200 and less than 400, the container state is considered healthy.
Brief Introduction

In the Kubernetes cluster, a kubelet process is started for each node nodes. Used to handle the tasks assigned to the master node, manage pod and container in pod. Each Kubelet process registers node information with the Apiserver, periodically reports resource usage to the master node, and monitors the container and node resources through Cadvise.

--node-sync-period: Sets the time period for synchronization--register-node parameter is set to True (default is True), Kubelet registers itself with Apiserver--kubeconfig: landing apiserver Required Directory--api-servers:apiserver address of credential/certificate

Key Structure

Type kubeletconfiguration struct slightly too much content

  type  Pod  struct  {metav1.
       Typemeta ' JSON:, inline '//Standard object ' s metadata. More Info:https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata//+optional Metav 1.ObjectMeta ' JSON: "Metadata,omitempty" Protobuf: "Bytes,1,opt,name=metadata" '//specification of the desired Beha
       Vior of the pod.
       More Info:https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status//+optional Spec Podspec ' JSON: "Spec,omitempty" Protobuf: "Bytes,2,opt,name=spec" '//Most recently observed status of the PO
       D.//This The data may isn't up to date.
       populated by the system.
       Read-only.
       More Info:https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status//+optional Status podstatus ' json: ' Status,omitempty ' protobuf: ' Bytes,3,opt,name=status '} 
is a collection of containers running on a host that is created and dispatched via the client to the hosts

one. Kubelet START process main entrance

Cmd/kubelet/kubelet.go source code is as follows:

FuncMain () {
       s: = options. Newkubeletserver ()
       s.addflags (pflag.commandline)

       flag. Initflags ()
       logs. Initlogs ()
       logs. Flushlogs ()

       Verflag. printandexitifrequested ()

       s.experimentaldockershim {
              err: = App. Rundockershim (&s.kubeletconfiguration, &s.containerruntimeoptions); Err!= Nil {
                     FMT. fprintf (OS. Stderr, "Error:%v\n", err)
                     OS. Exit (1)
              }

       err: = App. Run (s, nil); Err!= Nil {
              FMT. fprintf (OS. Stderr, "Error:%v\n", err)
              OS. Exit (1)
       }
}
Options. Newkubeletserver (): Creates an initialization verflag for kubeletserver structure logs. Printandexitifrequested (): Determines whether the parameter is help, and if so, direct print help exits. Finally, the key function app. Run (s, nil) Run Interface
funcRun (S *options. Kubeletserver, Kubedeps *kubelet. Kubeletdeps) (err Error) {//todo:this should is replaced by a--standalone flag standalonemode: = (len (s). apiserverlist) = = 0 &&!s.requirekubeconfig)ifS.exitonlockcontention && S.lockfilepath = "" { returnErrors. New ("Cannot exit on lock file Contention:no lock file specified") Does: = Make (Chan struct{})ifS.lockfilepath!= "" {glog.infof ("acquiring file lock on%q", S.lockfilepath)ifERR: = Flock. Acquire (S.lockfilepath); Err!= Nil { returnFmt. Errorf ("Unable to acquire file lock on%q:%v", S.lockfilepath, Err)}ifs.exitonlockcontention {glog.infof ("Watching for inotify events for:%v", S.lockfilepath)ifERR: = Watchforlockfilecontention (S.lockfilepath, done); Err!= Nil { returnERR}}//Set feature gates based on the value in Kubeletconfiguratio n Err = utilfeature. Defaultfeaturegate.set (S.kubeletconfiguration.featuregates)ifErr!= Nil { returnERR}
The whole process is a preliminary preparation, such as the preparation of some parameters.
unsecuredkubeletdeps () interface
funcUnsecuredkubeletdeps (S *options. Kubeletserver) (*kubelet. Kubeletdeps, error) {//Initialize the TLS Options tlsoptions, err: = Initializetls (&s.kubeletflags, &A Mp;s.kubeletconfiguration)ifErr!= Nil { returnNil, err} mounter: = mount. New (S.experimentalmounterpath)varWriter Kubeio. Writer = &kubeio. stdwriter{}ifs.containerized {Glog. V (2). Info ("Running Kubelet in containerized mode (experimental)") Mounter = mount. Newnsentermounter () writer = &kubeio. nsenterwriter{}}varDockerclient Libdocker. InterfaceifS.containerruntime = = Kubetypes. dockercontainerruntime {dockerclient = Libdocker. Connecttodockerordie (S.dockerendpoint, S.runtimerequesttimeout.duration, S.imagepullprogressdeadline. Duration)}Else{dockerclient = nil} return&kubelet.  kubeletdeps{Auth:nil,//default does not enforce AUTH[NZ] Cadvisorinterface: Nil,//cadvisor. New launches background processes (BG http. Listenandserve, and some BG cleaners), not set here Cloud:nil,//Cloud provider might start B Ackground processes Containermanager:nil, dockerclient:dockerclient, K Ubeclient:nil, Externalkubeclient:nil, Mounter:mounter, Ne Tworkplugins:probenetworkplugins (S.networkplugindir, S.cniconfdir, S.cnibindir), Oomadjuster:oo M.newoomadjuster (), Osinterface:kubecontainer. realos{}, Writer:writer, Volumeplugins:probevolumeplugins (s.volumeplugindir ), Tlsoptions:tlsoptions,}, nil}
Initializing the TLS certificate what Kubelet may be deployed as a container, need to configure standard output, if deployed into a container, there will be namespace quarantine issues, resulting in kubelet cannot access the Docker container namespace, so this will be judged, If you are running in a container, you need to use Nsenter, which can assist in Kubelet to the specified namespace Run command. Return to Kuneletdeps structure body
two. Kubelet Operation
Inside the Runkubelet, we see that it will eventually call the Startkublet function
  func    runkubelet (kubeflags *options. Kubeletflags, Kubecfg *componentconfig. Kubeletconfiguration, Kubedeps *kubelet.

       Kubeletdeps, runOnce bool, standalonemode bool) error {...............
       Process pods and exit.
                      if  runOnce { If  _, Err: = K.runonce (Podcfg.updates ()); Err!= Nil {  return  FMT. Errorf ("RunOnce failed:%v", err)} glog. Infof ("started Kubelet%s as RunOnce", version. Get (). String ())}  else  {startkubelet (k, podcfg, Kubecfg, Kubedeps) glog. Infof ("Started Kubelet%s", version. Get (). String ())}  return  nil} 
Run Kubelet main launch two functions, K.run () to enter the main loop, the execution of a pipeline, will be sent in real time the latest configuration information is K.run (Podcfg.updates ()), K.listenandserve () Start Kubele      API Services for T. Run's code is as follows:
func(KL *kubelet) Run (Updates <-ChanKubetypes. Podupdate) {//init modulers, such as Imagemanager, Containermanager, Oomwathcer, ResourceanalyzerifERR: = Kl.initializemodules (); Err!= Nil {kl.recorder.Eventf (kl.noderef, v1. Eventtypewarning, events. Kubeletsetupfailed, Err. Error ()) Glog. Error (Err) Kl.runtimeState.setInitError (ERR)}//Start volume Manager GoKl.volumeManager.Run (Kl.sourcesready, wait.) Neverstop)//Start up, update node status periodically to ApiserverifKl.kubeclient!= Nil {//Start syncing node status immediately, this could set up things the runtime to Run. GoWait. Until (Kl.syncnodestatus, Kl.nodestatusupdatefrequency, wait.) Neverstop)}//Up, timed synchronization network status GoWait. Until (Kl.syncnetworkstatus, 30*time. Second, wait. Neverstop) GoWait. Until (Kl.updateruntimeup, 5*time. Second, wait. Neverstop)

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.