--- title: "Kubelet Source Code Deep Dive: SyncLoop and PLEG" date: 2025-07-15 author: "haopengzhan" category: "Tech" tags: ["k8s", "kubernetes", "go", "cloud", "containers"] excerpt: "An in-depth exploration into the Kubernetes Kubelet runtime architecture, focusing on syncLoop mechanics and Pod Lifecycle Event Generator (PLEG)." cover: images/cover.svg lang: en --- Kubelet is the primary "node agent" that runs on each Kubernetes worker node. It registers the node with the apiserver, watches for PodSpec changes, and ensures containers described in those PodSpecs are running and healthy[^1]. ## Architectural Overview At the heart of the Kubelet daemon is the `syncLoop`. The syncLoop monitors multiple channels for pod changes: 1. **Config channel**: Pods from API server, file manifests, or HTTP endpoints. 2. **PLEG channel**: Pod Lifecycle Event Generator events. 3. **Probe channel**: Liveness and readiness probe results. 4. **Housekeeping channel**: Periodic cleanup tasks. ### The SyncLoop Implementation Here is a simplified view of how Kubelet receives events in Go: ```go func (kl *Kubelet) syncLoop(updates <-chan kubetypes.PodUpdate, handler SyncHandler) { klog.InfoS("Starting kubelet main sync loop") for { select { case u, ok := <-updates: if !ok { klog.ErrorS(nil, "Updates channel closed") return } handler.HandlePodAdditions(u.Pods) case e := <-kl.pleg.Watch(): handler.HandlePLEGEvent(e) } } } ``` ## Pod Lifecycle Event Generator (PLEG) PLEG periodically relists containers from the container runtime via CRI: ```bash # Inspecting runtime events with crictl crictl ps --state Running ``` If PLEG does not complete within the expected relist period (default 3 minutes), the node becomes `NotReady` with the condition `PLEG is not healthy`. ## Conclusion Understanding the syncLoop provides clear insights into why nodes report PLEG issues during disk I/O bottlenecks or heavy container churn. [^1]: Kubernetes documentation: https://kubernetes.io/docs/concepts/architecture/