kubelet 如何将事件同步到 apiserver?

How kubelet sync events to apiserver?

最近在研究kubelet sync events to apiserver 但是找不到代码在哪

kubelet 源可用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.

在 Kubelet 启动时,会创建一个 PodConfig 对象。 代码 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.

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

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

Op 定义 Pod 更改类型。例如,这些值可以是 ADDREMOVE。最后PodUpdate的所有类型都会被注入到podConfigupdates中。所以只需要监听update频道就可以得到本地节点的Pod配置更新。

Kubelet 启动完成后,执行syncLoop 函数。 代码 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
            }
            ...
    }

下面的文章详细解释了整个过程:Understanding the Kubelet Core Execution Frame