How kubelet sync events to apiserver?

1/7/2019

Recently I research how kubelet sync events to apiserver but I can't find where the code is.

-- kongshuo
kubelet
kubernetes
kubernetes-apiserver

1 Answer

1/7/2019

The source of kubelet is available here.

Kubelet can obtain Pod configurations required by the local node in multiple ways. The most important way is Apiserver. Kubelet can also obtain the Pod configurations by specifying the file directory or accessing the specified HTTP port.

On the startup of Kubelet, a PodConfig object is created. Code kubernetes/blob/master/pkg/kubelet/config/config.go#L58:

type PodConfig struct {
    pods *podStorage
    mux  *config.Mux

    // the channel of denormalized changes passed to listeners
    updates chan kubetypes.PodUpdate
    ...
}

PodConfig is essentially a multiplexer of Pod configurations. The built-in mux can listen on the sources of various Pod configurations (including apiserver, file, and http), and periodically synchronize the Pod configuration status of the sources.

Code kubernetes/blob/master/pkg/kubelet/types/pod_update.go#L80:

type PodUpdate struct {
    Pods   []*v1.Pod
    Op     PodOperation
    Source string
}

The Op defines the Pod change type. For example those can be values like ADD or REMOVE. In the end all types of PodUpdate will be injected to updates of podConfig. So there is only a need to listen to update channel to get Pod configuration updates of the local node.

Once Kubelet startup is complete, the syncLoop function is executed. Code kubernetes/blob/master/pkg/kubelet/kubelet.go#L180:

// syncLoop is the main loop for processing changes. It watches for changes from
// three channels (file, apiserver, and http) and creates a union of them. For
// any new change seen, will run a sync against desired state and running state. If
// no changes are seen to the configuration, will synchronize the last known desired
// state every sync-frequency seconds. Never returns.
    func (kl *Kubelet) syncLoop(updates <-chan kubetypes.PodUpdate, handler SyncHandler) {
        ...
        for {
            ...
            if !kl.syncLoopIteration(updates, handler, syncTicker.C, housekeepingTicker.C, plegCh) {
                break
            }
            ...
    }

The whole process is explained in detail in the following article: Understanding the Kubelet Core Execution Frame.

-- Crou
Source: StackOverflow