/*
Copyright 2014 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package kubelet

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/tools/record"
	runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/kubelet/events"
	"k8s.io/kubernetes/pkg/kubelet/eviction"
	"k8s.io/kubernetes/pkg/kubelet/metrics"
	kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
	"k8s.io/kubernetes/pkg/kubelet/util/queue"
	"k8s.io/utils/clock"
)

// OnCompleteFunc is a function that is invoked when an operation completes.
// If err is non-nil, the operation did not complete successfully.
type OnCompleteFunc func(err error)

// PodStatusFunc is a function that is invoked to override the pod status when a pod is killed.
type PodStatusFunc func(podStatus *v1.PodStatus)

//* OnCompleteFunc是一个在操作完成时被调用的函数。如果err非空,则操作完成不成功。
//* PodStatusFunc是一个函数,用于在杀死Pod时覆盖Pod的状态。

//* OnCompleteFunc是一个在操作完成时被调用的函数。
//如果err非空,则操作完成不成功。 * PodStatusFunc是一个函数,用于在杀死Pod时覆盖Pod的状态。

// KillPodOptions are options when performing a pod update whose update type is kill.
type KillPodOptions struct {
	// CompletedCh is closed when the kill request completes (syncTerminatingPod has completed
	// without error) or if the pod does not exist, or if the pod has already terminated. This
	// could take an arbitrary amount of time to be closed, but is never left open once
	// CouldHaveRunningContainers() returns false.
	CompletedCh chan<- struct{}
	// Evict is true if this is a pod triggered eviction - once a pod is evicted some resources are
	// more aggressively reaped than during normal pod operation (stopped containers).
	Evict bool
	// PodStatusFunc is invoked (if set) and overrides the status of the pod at the time the pod is killed.
	// The provided status is populated from the latest state.
	PodStatusFunc PodStatusFunc
	// PodTerminationGracePeriodSecondsOverride is optional override to use if a pod is being killed as part of kill operation.
	PodTerminationGracePeriodSecondsOverride *int64
}

//KillPodOptions是一个结构体,用于表示执行pod更新时的kill选项。
//它包含以下字段:
//- CompletedCh:一个通道,当kill请求完成(syncTerminatingPod已完成且无错误)或pod不存在或pod已经终止时,会关闭此通道。
//这可能需要任意长的时间来关闭,但一旦CouldHaveRunningContainers()返回false,它就不会再打开。
//- Evict:一个布尔值,如果为true,则表示这是由pod触发的驱逐,一旦pod被驱逐,一些资源会比正常pod操作时更激进地被回收(已停止的容器)。
//- PodStatusFunc:一个函数,如果设置,会在kill pod时被调用,并覆盖pod的状态。提供的状态从最新状态中填充。
//- PodTerminationGracePeriodSecondsOverride:一个可选的字段,如果pod作为kill操作的一部分被终止
//,则可以使用此字段作为pod终止的优雅期限的覆盖值。

// UpdatePodOptions is an options struct to pass to a UpdatePod operation.
type UpdatePodOptions struct {
	// The type of update (create, update, sync, kill).
	UpdateType kubetypes.SyncPodType
	// StartTime is an optional timestamp for when this update was created. If set,
	// when this update is fully realized by the pod worker it will be recorded in
	// the PodWorkerDuration metric.
	StartTime time.Time
	// Pod to update. Required.
	Pod *v1.Pod
	// MirrorPod is the mirror pod if Pod is a static pod. Optional when UpdateType
	// is kill or terminated.
	MirrorPod *v1.Pod
	// RunningPod is a runtime pod that is no longer present in config. Required
	// if Pod is nil, ignored if Pod is set.
	RunningPod *kubecontainer.Pod
	// KillPodOptions is used to override the default termination behavior of the
	// pod or to update the pod status after an operation is completed. Since a
	// pod can be killed for multiple reasons, PodStatusFunc is invoked in order
	// and later kills have an opportunity to override the status (i.e. a preemption
	// may be later turned into an eviction).
	KillPodOptions *KillPodOptions
}

//UpdatePodOptions是一个用于传递给UpdatePod操作的选项结构体。
//该结构体包含以下字段:
//- UpdateType:更新类型,包括创建、更新、同步和终止。
//- StartTime:可选的时间戳,表示更新创建的时间。
//如果设置,当更新被Pod工作线程完全实现时,将被记录在PodWorkerDuration指标中。
//- Pod:要更新的Pod对象。必需。
//- MirrorPod:如果Pod是静态Pod,则为镜像Pod。
//当更新类型为终止或已终止时,该字段为可选。
//- RunningPod:一个运行时Pod,不再存在于配置中。
//如果Pod为nil,则该字段必需,否则将被忽略。
//- KillPodOptions:用于覆盖Pod的默认终止行为,或在操作完成后更新Pod状态。
//由于Pod可能由于多个原因被终止,
//因此会按顺序调用PodStatusFunc,并且后来的终止操作有机会覆盖状态(例如,抢占可能被转换为驱逐)。

// PodWorkType classifies the status of pod as seen by the pod worker - setup (sync),
// teardown of containers (terminating), or cleanup (terminated).
type PodWorkerState int

const (
	// SyncPod is when the pod is expected to be started and running.
	SyncPod PodWorkerState = iota
	// TerminatingPod is when the pod is no longer being set up, but some
	// containers may be running and are being torn down.
	TerminatingPod
	// TerminatedPod indicates the pod is stopped, can have no more running
	// containers, and any foreground cleanup can be executed.
	TerminatedPod
)

//这段代码定义了一个名为PodWorkerState的常量类型,并用iota为每个常量赋予了递增的整数值。
//其中,SyncPod表示Pod应该被启动并运行的状态;
//TerminatingPod表示Pod不再被设置,但可能有一些容器正在被关闭的状态;
//TerminatedPod表示Pod已经停止,不能再有运行中的容器,并且可以执行任何前景清理的状态。

func (state PodWorkerState) String() string {
	switch state {
	case SyncPod:
		return "sync"
	case TerminatingPod:
		return "terminating"
	case TerminatedPod:
		return "terminated"
	default:
		panic(fmt.Sprintf("the state %d is not defined", state))
	}
}

//该函数是一个自定义的String方法,用于将PodWorkerState类型的值转换为对应的字符串表示。
//根据case的不同,分别返回"sync"、"terminating"和"terminated"。
//如果传入的state值不属于已定义的状态,将会触发panic异常。

// PodWorkerSync is the summarization of a single pod worker for sync. Values
// besides state are used to provide metric counts for operators.
type PodWorkerSync struct {
	// State of the pod.
	State PodWorkerState
	// Orphan is true if the pod is no longer in the desired set passed to SyncKnownPods.
	Orphan bool
	// HasConfig is true if we have a historical pod spec for this pod.
	HasConfig bool
	// Static is true if we have config and the pod came from a static source.
	Static bool
}

//该代码定义了一个名为PodWorkerSync的结构体,用于总结单个Pod worker的同步状态。
//该结构体包含以下字段:
//- State:Pod的工作状态。
//- Orphan:如果Pod不再是在SyncKnownPods中传递的期望集合中,则为true。
//- HasConfig:如果我们有该Pod的历史规范,则为true。
//- Static:如果我们有配置且Pod来自静态源,则为true。

// podWork is the internal changes
type podWork struct {
	// WorkType is the type of sync to perform - sync (create), terminating (stop
	// containers), terminated (clean up and write status).
	WorkType PodWorkerState

	// Options contains the data to sync.
	Options UpdatePodOptions
}

//这段代码定义了一个名为podWork的结构体,它用于表示Pod的工作类型和同步选项。
//podWork结构体包含两个字段:
//1. WorkType:表示要执行的同步类型,可以是创建(sync)、停止容器(terminating)或清理并写入状态(terminated)。
//2. Options:包含了同步所需的数据,具体为UpdatePodOptions类型。

// PodWorkers is an abstract interface for testability.
type PodWorkers interface {
	// UpdatePod notifies the pod worker of a change to a pod, which will then
	// be processed in FIFO order by a goroutine per pod UID. The state of the
	// pod will be passed to the syncPod method until either the pod is marked
	// as deleted, it reaches a terminal phase (Succeeded/Failed), or the pod
	// is evicted by the kubelet. Once that occurs the syncTerminatingPod method
	// will be called until it exits successfully, and after that all further
	// UpdatePod() calls will be ignored for that pod until it has been forgotten
	// due to significant time passing. A pod that is terminated will never be
	// restarted.
	UpdatePod(options UpdatePodOptions)
	// SyncKnownPods removes workers for pods that are not in the desiredPods set
	// and have been terminated for a significant period of time. Once this method
	// has been called once, the workers are assumed to be fully initialized and
	// subsequent calls to ShouldPodContentBeRemoved on unknown pods will return
	// true. It returns a map describing the state of each known pod worker. It
	// is the responsibility of the caller to re-add any desired pods that are not
	// returned as knownPods.
	SyncKnownPods(desiredPods []*v1.Pod) (knownPods map[types.UID]PodWorkerSync)

	// IsPodKnownTerminated returns true once SyncTerminatingPod completes
	// successfully - the provided pod UID it is known by the pod
	// worker to be terminated. If the pod has been force deleted and the pod worker
	// has completed termination this method will return false, so this method should
	// only be used to filter out pods from the desired set such as in admission.
	//
	// Intended for use by the kubelet config loops, but not subsystems, which should
	// use ShouldPod*().
	IsPodKnownTerminated(uid types.UID) bool
	// CouldHaveRunningContainers returns true before the pod workers have synced,
	// once the pod workers see the pod (syncPod could be called), and returns false
	// after the pod has been terminated (running containers guaranteed stopped).
	//
	// Intended for use by the kubelet config loops, but not subsystems, which should
	// use ShouldPod*().
	CouldHaveRunningContainers(uid types.UID) bool

	// ShouldPodBeFinished returns true once SyncTerminatedPod completes
	// successfully - the provided pod UID it is known to the pod worker to
	// be terminated and have resources reclaimed. It returns false before the
	// pod workers have synced (syncPod could be called). Once the pod workers
	// have synced it returns false if the pod has a sync status until
	// SyncTerminatedPod completes successfully. If the pod workers have synced,
	// but the pod does not have a status it returns true.
	//
	// Intended for use by subsystem sync loops to avoid performing background setup
	// after termination has been requested for a pod. Callers must ensure that the
	// syncPod method is non-blocking when their data is absent.
	ShouldPodBeFinished(uid types.UID) bool
	// IsPodTerminationRequested returns true when pod termination has been requested
	// until the termination completes and the pod is removed from config. This should
	// not be used in cleanup loops because it will return false if the pod has already
	// been cleaned up - use ShouldPodContainersBeTerminating instead. Also, this method
	// may return true while containers are still being initialized by the pod worker.
	//
	// Intended for use by the kubelet sync* methods, but not subsystems, which should
	// use ShouldPod*().
	IsPodTerminationRequested(uid types.UID) bool

	// ShouldPodContainersBeTerminating returns false before pod workers have synced,
	// or once a pod has started terminating. This check is similar to
	// ShouldPodRuntimeBeRemoved but is also true after pod termination is requested.
	//
	// Intended for use by subsystem sync loops to avoid performing background setup
	// after termination has been requested for a pod. Callers must ensure that the
	// syncPod method is non-blocking when their data is absent.
	ShouldPodContainersBeTerminating(uid types.UID) bool
	// ShouldPodRuntimeBeRemoved returns true if runtime managers within the Kubelet
	// should aggressively cleanup pod resources that are not containers or on disk
	// content, like attached volumes. This is true when a pod is not yet observed
	// by a worker after the first sync (meaning it can't be running yet) or after
	// all running containers are stopped.
	// TODO: Once pod logs are separated from running containers, this method should
	// be used to gate whether containers are kept.
	//
	// Intended for use by subsystem sync loops to know when to start tearing down
	// resources that are used by running containers. Callers should ensure that
	// runtime content they own is not required for post-termination - for instance
	// containers are required in docker to preserve pod logs until after the pod
	// is deleted.
	ShouldPodRuntimeBeRemoved(uid types.UID) bool
	// ShouldPodContentBeRemoved returns true if resource managers within the Kubelet
	// should aggressively cleanup all content related to the pod. This is true
	// during pod eviction (when we wish to remove that content to free resources)
	// as well as after the request to delete a pod has resulted in containers being
	// stopped (which is a more graceful action). Note that a deleting pod can still
	// be evicted.
	//
	// Intended for use by subsystem sync loops to know when to start tearing down
	// resources that are used by non-deleted pods. Content is generally preserved
	// until deletion+removal_from_etcd or eviction, although garbage collection
	// can free content when this method returns false.
	ShouldPodContentBeRemoved(uid types.UID) bool
	// IsPodForMirrorPodTerminatingByFullName returns true if a static pod with the
	// provided pod name is currently terminating and has yet to complete. It is
	// intended to be used only during orphan mirror pod cleanup to prevent us from
	// deleting a terminating static pod from the apiserver before the pod is shut
	// down.
	IsPodForMirrorPodTerminatingByFullName(podFullname string) bool
}

//该接口定义了一个PodWorkers接口,包含多个方法,用于管理Pod的工作线程。
//其中,UpdatePod方法用于通知Pod工作线程某个Pod发生了变化,SyncKnownPods方法用于同步已知的Pod,并移除不在期望Pod集中的工作线程。
//IsPodKnownTerminated方法用于判断某个Pod是否已知终止,
//CouldHaveRunningContainers方法用于判断某个Pod是否可能有运行中的容器,
//ShouldPodBeFinished方法用于判断某个Pod是否应该完成,
//IsPodTerminationRequested方法用于判断是否请求终止某个Pod,
//ShouldPodContainersBeTerminating方法用于判断是否应该终止某个Pod的容器 ,
//ShouldPodRuntimeBeRemoved方法用于判断是否应该移除某个Pod的运行时资源,
//ShouldPodContentBeRemoved方法用于判断是否应该移除某个Pod的内容,
//IsPodForMirrorPodTerminatingByFullName方法用于判断某个静态Pod是否正在终止。

// podSyncer describes the core lifecyle operations of the pod state machine. A pod is first
// synced until it naturally reaches termination (true is returned) or an external agent decides
// the pod should be terminated. Once a pod should be terminating, SyncTerminatingPod is invoked
// until it returns no error. Then the SyncTerminatedPod method is invoked until it exits without
// error, and the pod is considered terminal. Implementations of this interface must be threadsafe
// for simultaneous invocation of these methods for multiple pods.
type podSyncer interface {
	// SyncPod configures the pod and starts and restarts all containers. If it returns true, the
	// pod has reached a terminal state and the presence of the error indicates succeeded or failed.
	// If an error is returned, the sync was not successful and should be rerun in the future. This
	// is a long running method and should exit early with context.Canceled if the context is canceled.
	SyncPod(ctx context.Context, updateType kubetypes.SyncPodType, pod *v1.Pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, error)
	// SyncTerminatingPod attempts to ensure the pod's containers are no longer running and to collect
	// any final status. This method is repeatedly invoked with diminishing grace periods until it exits
	// without error. Once this method exits with no error other components are allowed to tear down
	// supporting resources like volumes and devices. If the context is canceled, the method should
	// return context.Canceled unless it has successfully finished, which may occur when a shorter
	// grace period is detected.
	SyncTerminatingPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error
	// SyncTerminatingRuntimePod is invoked when running containers are found that correspond to
	// a pod that is no longer known to the kubelet to terminate those containers. It should not
	// exit without error unless all containers are known to be stopped.
	SyncTerminatingRuntimePod(ctx context.Context, runningPod *kubecontainer.Pod) error
	// SyncTerminatedPod is invoked after all running containers are stopped and is responsible
	// for releasing resources that should be executed right away rather than in the background.
	// Once it exits without error the pod is considered finished on the node.
	SyncTerminatedPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error
}

//这段代码定义了一个名为podSyncer的接口,该接口描述了Pod状态机的核心生命周期操作。
//接口中有四个方法:
//1. SyncPod:配置Pod并启动和重启所有容器。如果返回true,则Pod已达到终止状态,错误的存在表示成功或失败。
//如果返回错误,则同步不成功,应在将来重新运行。
//这是一个长时间运行的方法,如果上下文被取消,应该早期退出并返回context.Canceled。
//2. SyncTerminatingPod:确保Pod的容器不再运行,并收集最终状态。
//此方法会被重复调用,直到无错误退出。一旦此方法无错误退出,其他组件就可以拆除支持资源,如卷和设备。
//如果上下文被取消,方法应该返回context.Canceled,除非它已成功完成,这可能在检测到较短的宽限期时发生。
//3. SyncTerminatingRuntimePod:当发现与kubelet不再知道要终止的Pod相对应的正在运行的容器时,将调用此方法来终止这些容器。
//除非所有容器已知已停止,否则它不应该无错误退出。
//4. SyncTerminatedPod:在所有正在运行的容器停止后被调用,负责释放应立即执行而不是在后台执行的资源。
//一旦它无错误退出,Pod就被认为在节点上完成。

type syncPodFnType func(ctx context.Context, updateType kubetypes.SyncPodType, pod *v1.Pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, error)
type syncTerminatingPodFnType func(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error
type syncTerminatingRuntimePodFnType func(ctx context.Context, runningPod *kubecontainer.Pod) error
type syncTerminatedPodFnType func(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error

// podSyncerFuncs implements podSyncer and accepts functions for each method.
type podSyncerFuncs struct {
	syncPod                   syncPodFnType
	syncTerminatingPod        syncTerminatingPodFnType
	syncTerminatingRuntimePod syncTerminatingRuntimePodFnType
	syncTerminatedPod         syncTerminatedPodFnType
}

//这段代码定义了四个函数类型和一个结构体。
//- syncPodFnType 是一个函数类型,
//它接受五个参数:ctx context.Context、updateType kubetypes.SyncPodType、pod *v1.Pod、mirrorPod *v1.Pod、podStatus *kubecontainer.PodStatus,并返回两个值:bool 和 error。
//- syncTerminatingPodFnType 是一个函数类型,它接受四个参数:ctx context.Context、pod *v1.Pod、podStatus *kubecontainer.PodStatus、gracePeriod *int64、podStatusFn func(*v1.PodStatus),
//并返回一个错误值。
//- syncTerminatingRuntimePodFnType 是一个函数类型,
//它接受一个参数 ctx context.Context 和一个 runningPod *kubecontainer.Pod,并返回一个错误值。
//- syncTerminatedPodFnType 是一个函数类型,它接受两个参数:ctx context.Context、pod *v1.Pod、podStatus *kubecontainer.PodStatus,并返回一个错误值。
//- podSyncerFuncs 是一个结构体,它包含了上述四个函数类型的字段。
//这些函数类型和结构体用于实现 podSyncer 接口,并允许通过函数来实现接口的方法。

func newPodSyncerFuncs(s podSyncer) podSyncerFuncs {
	return podSyncerFuncs{
		syncPod:                   s.SyncPod,
		syncTerminatingPod:        s.SyncTerminatingPod,
		syncTerminatingRuntimePod: s.SyncTerminatingRuntimePod,
		syncTerminatedPod:         s.SyncTerminatedPod,
	}
}

//这段Go代码定义了一个newPodSyncerFuncs函数,用于创建一个podSyncerFuncs结构体实例。
//函数接受一个实现了podSyncer接口的参数s,并根据s的实现,初始化一个podSyncerFuncs结构体实例。
//具体来说,将s的SyncPod、SyncTerminatingPod、SyncTerminatingRuntimePod和SyncTerminatedPod方法的引用赋值给podSyncerFuncs结构体的相应字段。
//这样,通过调用newPodSyncerFuncs函数,可以创建一个包含具体同步逻辑的podSyncerFuncs实例,用于后续的Pod状态同步操作。

var _ podSyncer = podSyncerFuncs{}

func (f podSyncerFuncs) SyncPod(ctx context.Context, updateType kubetypes.SyncPodType, pod *v1.Pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, error) {
	return f.syncPod(ctx, updateType, pod, mirrorPod, podStatus)
}
func (f podSyncerFuncs) SyncTerminatingPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error {
	return f.syncTerminatingPod(ctx, pod, podStatus, gracePeriod, podStatusFn)
}
func (f podSyncerFuncs) SyncTerminatingRuntimePod(ctx context.Context, runningPod *kubecontainer.Pod) error {
	return f.syncTerminatingRuntimePod(ctx, runningPod)
}
func (f podSyncerFuncs) SyncTerminatedPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error {
	return f.syncTerminatedPod(ctx, pod, podStatus)
}

//这段Go代码定义了一个podSyncer接口和一个实现了该接口的podSyncerFuncs结构体。
//podSyncer接口定义了四个方法,用于同步Pod的状态。
//podSyncerFuncs结构体通过实现podSyncer接口的方法,定义了具体的行为。其中:
//- SyncPod方法用于同步Pod的状态,根据传入的参数调用f.syncPod方法。
//- SyncTerminatingPod方法用于同步正在终止的Pod的状态,根据传入的参数调用f.syncTerminatingPod方法。
//- SyncTerminatingRuntimePod方法用于同步正在终止的运行时Pod的状态,根据传入的参数调用f.syncTerminatingRuntimePod方法。
//- SyncTerminatedPod方法用于同步已终止的Pod的状态,根据传入的参数调用f.syncTerminatedPod方法。
//这些方法的实现可以根据具体业务逻辑进行定制。

const (
	// jitter factor for resyncInterval
	workerResyncIntervalJitterFactor = 0.5

	// jitter factor for backOffPeriod and backOffOnTransientErrorPeriod
	workerBackOffPeriodJitterFactor = 0.5

	// backoff period when transient error occurred.
	backOffOnTransientErrorPeriod = time.Second
)

//这段Go代码定义了一些常量。
//- workerResyncIntervalJitterFactor是用于resyncInterval的抖动因子,其值为0.5。
//- workerBackOffPeriodJitterFactor是用于backOffPeriod和backOffOnTransientErrorPeriod的抖动因子,其值为0.5。
//- backOffOnTransientErrorPeriod是在发生临时错误时的退避周期,其值为1秒。

// podSyncStatus tracks per-pod transitions through the three phases of pod
// worker sync (setup, terminating, terminated).
type podSyncStatus struct {
	// ctx is the context that is associated with the current pod sync.
	// TODO: remove this from the struct by having the context initialized
	// in startPodSync, the cancelFn used by UpdatePod, and cancellation of
	// a parent context for tearing down workers (if needed) on shutdown
	ctx context.Context
	// cancelFn if set is expected to cancel the current podSyncer operation.
	cancelFn context.CancelFunc

	// fullname of the pod
	fullname string

	// working is true if an update is pending or being worked by a pod worker
	// goroutine.
	working bool
	// pendingUpdate is the updated state the pod worker should observe. It is
	// cleared and moved to activeUpdate when a pod worker reads it. A new update
	// may always replace a pending update as the pod worker does not guarantee
	// that all intermediate states are synced to a worker, only the most recent.
	// This state will not be visible to downstream components until a pod worker
	// has begun processing it.
	pendingUpdate *UpdatePodOptions
	// activeUpdate is the most recent version of the pod's state that will be
	// passed to a sync*Pod function. A pod becomes visible to downstream components
	// once a worker decides to start a pod (startedAt is set). The pod and mirror
	// pod fields are accumulated if they are missing on a particular call (the last
	// known version), and the value of KillPodOptions is accumulated as pods cannot
	// have their grace period shortened. This is the source of truth for the pod spec
	// the kubelet is reconciling towards for all components that act on running pods.
	activeUpdate *UpdatePodOptions

	// syncedAt is the time at which the pod worker first observed this pod.
	syncedAt time.Time
	// startedAt is the time at which the pod worker allowed the pod to start.
	startedAt time.Time
	// terminatingAt is set once the pod is requested to be killed - note that
	// this can be set before the pod worker starts terminating the pod, see
	// terminating.
	terminatingAt time.Time
	// terminatedAt is set once the pod worker has completed a successful
	// syncTerminatingPod call and means all running containers are stopped.
	terminatedAt time.Time
	// gracePeriod is the requested gracePeriod once terminatingAt is nonzero.
	gracePeriod int64
	// notifyPostTerminating will be closed once the pod transitions to
	// terminated. After the pod is in terminated state, nothing should be
	// added to this list.
	notifyPostTerminating []chan<- struct{}
	// statusPostTerminating is a list of the status changes associated
	// with kill pod requests. After the pod is in terminated state, nothing
	// should be added to this list. The worker will execute the last function
	// in this list on each termination attempt.
	statusPostTerminating []PodStatusFunc

	// startedTerminating is true once the pod worker has observed the request to
	// stop a pod (exited syncPod and observed a podWork with WorkType
	// TerminatingPod). Once this is set, it is safe for other components
	// of the kubelet to assume that no other containers may be started.
	startedTerminating bool
	// deleted is true if the pod has been marked for deletion on the apiserver
	// or has no configuration represented (was deleted before).
	deleted bool
	// evicted is true if the kill indicated this was an eviction (an evicted
	// pod can be more aggressively cleaned up).
	evicted bool
	// finished is true once the pod worker completes for a pod
	// (syncTerminatedPod exited with no errors) until SyncKnownPods is invoked
	// to remove the pod. A terminal pod (Succeeded/Failed) will have
	// termination status until the pod is deleted.
	finished bool
	// restartRequested is true if the pod worker was informed the pod is
	// expected to exist (update type of create, update, or sync) after
	// it has been killed. When known pods are synced, any pod that is
	// terminated and has restartRequested will have its history cleared.
	restartRequested bool
	// observedRuntime is true if the pod has been observed to be present in the
	// runtime. A pod that has been observed at runtime must go through either
	// SyncTerminatingRuntimePod or SyncTerminatingPod. Otherwise, we can avoid
	// invoking the terminating methods if the pod is deleted or orphaned before
	// it has been started.
	observedRuntime bool
}

//这段代码定义了一个名为podSyncStatus的结构体,用于跟踪Pod通过三个阶段(setup、terminating、terminated)的同步状态。
//该结构体包含以下字段:
//- ctx:与当前Pod同步相关的上下文。
//- cancelFn:如果设置,预期用于取消当前的podSyncer操作。
//- fullname:Pod的完整名称。
//- working:如果存在更新待处理或被Pod工作线程处理,则为true。
//- pendingUpdate:Pod工作线程应观察的更新状态。
//当Pod工作线程读取它时,将被清除并移动到activeUpdate。
//新的更新可以随时替换待处理的更新,因为Pod工作线程不保证同步所有中间状态,只保证同步最新的状态。
//此状态在Pod工作线程开始处理之前不会对下游组件可见。
//- activeUpdate:Pod状态的最新版本,将传递给sync*Pod函数。
//Pod对下游组件可见时,一旦Pod工作线程决定启动Pod(startedAt被设置),就会开始处理。
//pod和mirror pod字段如果缺少,则会累积(最后一次已知版本),而KillPodOptions的值会累积,因为Pod不能缩短其宽限期。
//这是kubelet为所有操作运行中Pod的组件进行协调的Pod规范的真相来源。
//- syncedAt:Pod工作线程首次观察到此Pod的时间。
//- startedAt:Pod工作线程允许Pod启动的时间。
//- terminatingAt:一旦请求杀死Pod,则设置此时间。
//请注意,这可能在Pod工作线程开始终止Pod之前设置(see terminating)。
//- terminatedAt:一旦Pod工作线程成功完成syncTerminatingPod调用,表示所有运行中的容器已停止,则设置此时间。
//- gracePeriod:一旦terminatingAt非零,则为请求的宽限期。
//- notifyPostTerminating:一旦Pod转换为terminated状态,将关闭此列表。
//在Pod处于terminated状态后,不应向此列表添加任何内容。
//- statusPostTerminating:与kill pod请求相关联的状态更改列表。
//在Pod处于terminated状态后,不应向此列表添加任何内容。工作线程将在每次终止尝试时执行此列表中的最后一个函数。
//- startedTerminating:一旦Pod工作线程停止Pod(退出syncPod并观察到具有WorkType TerminatingPod的podWork),则设置为true。
//一旦设置此值,其他kubelet组件可以安全地假设不会启动其他容器。
//- deleted:如果Pod在apiserver上被标记为删除,或者没有表示配置(在删除之前被删除),则为true。
//- evicted:如果终止指示这是驱逐(被驱逐的Pod可以更积极地进行清理),则为true。
//- finished:一旦Pod工作线程完成Pod的同步(syncTerminatedPod退出且无错误),直到SyncKnownPods被调用以删除Pod。
//一个终止状态的Pod(Succeeded/Failed)将具有终止状态,直到被删除。
//- restartRequested:如果Pod工作线程被告知Pod在被杀死后预期存在(更新类型为create、update或sync),则为true。
//当已知Pods被同步时,任何终止且restartRequested为true的Pod将清除其历史记录。
//- observedRuntime:如果Pod已被观察到存在于运行时,则为true。
//一个在运行时被观察到的Pod必须经过SyncTerminatingRuntimePod或SyncTerminatingPod中的一个。
//否则,如果Pod在启动之前被删除或被遗弃,我们可以避免调用终止方法。

func (s *podSyncStatus) IsWorking() bool              { return s.working }
func (s *podSyncStatus) IsTerminationRequested() bool { return !s.terminatingAt.IsZero() }
func (s *podSyncStatus) IsTerminationStarted() bool   { return s.startedTerminating }
func (s *podSyncStatus) IsTerminated() bool           { return !s.terminatedAt.IsZero() }
func (s *podSyncStatus) IsFinished() bool             { return s.finished }
func (s *podSyncStatus) IsEvicted() bool              { return s.evicted }
func (s *podSyncStatus) IsDeleted() bool              { return s.deleted }
func (s *podSyncStatus) IsStarted() bool              { return !s.startedAt.IsZero() }

// WorkType returns this pods' current state of the pod in pod lifecycle state machine.
func (s *podSyncStatus) WorkType() PodWorkerState {
	if s.IsTerminated() {
		return TerminatedPod
	}
	if s.IsTerminationRequested() {
		return TerminatingPod
	}
	return SyncPod
}

//这段代码定义了一个名为podSyncStatus的结构体的几个方法。这个结构体用来表示Pod的同步状态。
//1. IsWorking()方法返回一个布尔值,表示Pod是否正在工作。它直接返回s.working的值。
//2. IsTerminationRequested()方法返回一个布尔值,表示是否请求了终止Pod。它通过判断s.terminatingAt是否为零值来决定。
//3. IsTerminationStarted()方法返回一个布尔值,表示是否已经开始终止Pod。它直接返回s.startedTerminating的值。
//4. IsTerminated()方法返回一个布尔值,表示Pod是否已经终止。 它通过判断s.terminatedAt是否为零值来决定。
//5. IsFinished()方法返回一个布尔值,表示Pod是否已经完成。它直接返回s.finished的值。
//6. IsEvicted()方法返回一个布尔值,表示Pod是否被驱逐。它直接返回s.evicted的值。
//7. IsDeleted()方法返回一个布尔值,表示Pod是否被删除。它直接返回s.deleted的值。
//8. IsStarted()方法返回一个布尔值,表示Pod是否已经开始。它通过判断s.startedAt是否为零值来决定。
//9. WorkType()方法返回一个PodWorkerState类型的值,表示Pod当前在Pod生命周期状态机中的状态。
//它根据Pod是否终止或是否请求终止来返回不同的状态值:TerminatedPod、TerminatingPod或SyncPod。

// mergeLastUpdate records the most recent state from a new update. Pod and MirrorPod are
// incremented. KillPodOptions is accumulated. If RunningPod is set, Pod is synthetic and
// will *not* be used as the last pod state unless no previous pod state exists (because
// the pod worker may be responsible for terminating a pod from a previous run of the
// kubelet where no config state is visible). The contents of activeUpdate are used as the
// source of truth for components downstream of the pod workers.
func (s *podSyncStatus) mergeLastUpdate(other UpdatePodOptions) {
	opts := s.activeUpdate
	if opts == nil {
		opts = &UpdatePodOptions{}
		s.activeUpdate = opts
	}

	// UpdatePodOptions states (and UpdatePod enforces) that either Pod or RunningPod
	// is set, and we wish to preserve the most recent Pod we have observed, so only
	// overwrite our Pod when we have no Pod or when RunningPod is nil.
	if opts.Pod == nil || other.RunningPod == nil {
		opts.Pod = other.Pod
	}
	// running pods will not persist but will be remembered for replay
	opts.RunningPod = other.RunningPod
	// if mirrorPod was not provided, remember the last one for replay
	if other.MirrorPod != nil {
		opts.MirrorPod = other.MirrorPod
	}
	// accumulate kill pod options
	if other.KillPodOptions != nil {
		opts.KillPodOptions = &KillPodOptions{}
		if other.KillPodOptions.Evict {
			opts.KillPodOptions.Evict = true
		}
		if override := other.KillPodOptions.PodTerminationGracePeriodSecondsOverride; override != nil {
			value := *override
			opts.KillPodOptions.PodTerminationGracePeriodSecondsOverride = &value
		}
	}
	// StartTime is not copied - that is purely for tracking latency of config propagation
	// from kubelet to pod worker.
}

//该函数用于合并两个Pod的状态信息,将另一个UpdatePodOptions类型的other对象的属性值合并到s对象的activeUpdate属性中。
//主要合并了Pod、RunningPod、MirrorPod和KillPodOptions等属性。
//其中,Pod属性只有在s对象的activeUpdate属性中的Pod为空或other对象的RunningPod为空时才会被更新。
//MirrorPod属性会被更新为other对象的MirrorPod属性值,而KillPodOptions属性则会进行累积。
//函数的最后,指出了StartTime属性不会被复制,因为它仅用于跟踪配置传播的延迟时间。

// podWorkers keeps track of operations on pods and ensures each pod is
// reconciled with the container runtime and other subsystems. The worker
// also tracks which pods are in flight for starting, which pods are
// shutting down but still have running containers, and which pods have
// terminated recently and are guaranteed to have no running containers.
//
// podWorkers is the source of truth for what pods should be active on a
// node at any time, and is kept up to date with the desired state of the
// node (tracked by the kubelet pod config loops and the state in the
// kubelet's podManager) via the UpdatePod method. Components that act
// upon running pods should look to the pod worker for state instead of the
// kubelet podManager. The pod worker is periodically reconciled with the
// state of the podManager via SyncKnownPods() and is responsible for
// ensuring the completion of all observed pods no longer present in
// the podManager (no longer part of the node's desired config).
//
// A pod passed to a pod worker is either being synced (expected to be
// running), terminating (has running containers but no new containers are
// expected to start), terminated (has no running containers but may still
// have resources being consumed), or cleaned up (no resources remaining).
// Once a pod is set to be "torn down" it cannot be started again for that
// UID (corresponding to a delete or eviction) until:
//
//  1. The pod worker is finalized (syncTerminatingPod and
//     syncTerminatedPod exit without error sequentially)
//  2. The SyncKnownPods method is invoked by kubelet housekeeping and the pod
//     is not part of the known config.
//
// Pod workers provide a consistent source of information to other kubelet
// loops about the status of the pod and whether containers can be
// running. The ShouldPodContentBeRemoved() method tracks whether a pod's
// contents should still exist, which includes non-existent pods after
// SyncKnownPods() has been called once (as per the contract, all existing
// pods should be provided via UpdatePod before SyncKnownPods is invoked).
// Generally other sync loops are expected to separate "setup" and
// "teardown" responsibilities and the information methods here assist in
// each by centralizing that state. A simple visualization of the time
// intervals involved might look like:
//
// ---|                                         = kubelet config has synced at least once
// -------|                                  |- = pod exists in apiserver config
// --------|                  |---------------- = CouldHaveRunningContainers() is true
//
//	^- pod is observed by pod worker  .
//	.                                 .
//
// ----------|       |------------------------- = syncPod is running
//
//	. ^- pod worker loop sees change and invokes syncPod
//	. .                               .
//
// --------------|                     |------- = ShouldPodContainersBeTerminating() returns true
// --------------|                     |------- = IsPodTerminationRequested() returns true (pod is known)
//
//	. .   ^- Kubelet evicts pod       .
//	. .                               .
//
// -------------------|       |---------------- = syncTerminatingPod runs then exits without error
//
//	        . .        ^ pod worker loop exits syncPod, sees pod is terminating,
//					 . .          invokes syncTerminatingPod
//	        . .                               .
//
// ---|    |------------------|              .  = ShouldPodRuntimeBeRemoved() returns true (post-sync)
//
//	.                ^ syncTerminatingPod has exited successfully
//	.                               .
//
// ----------------------------|       |------- = syncTerminatedPod runs then exits without error
//
//	.                         ^ other loops can tear down
//	.                               .
//
// ------------------------------------|  |---- = status manager is waiting for SyncTerminatedPod() finished
//
//	.                         ^     .
//
// ----------|                               |- = status manager can be writing pod status
//
//	^ status manager deletes pod because no longer exists in config
//
// Other components in the Kubelet can request a termination of the pod
// via the UpdatePod method or the killPodNow wrapper - this will ensure
// the components of the pod are stopped until the kubelet is restarted
// or permanently (if the phase of the pod is set to a terminal phase
// in the pod status change).
type podWorkers struct {
	// Protects all per worker fields.
	podLock sync.Mutex
	// podsSynced is true once the pod worker has been synced at least once,
	// which means that all working pods have been started via UpdatePod().
	podsSynced bool

	// Tracks all running per-pod goroutines - per-pod goroutine will be
	// processing updates received through its corresponding channel. Sending
	// a message on this channel will signal the corresponding goroutine to
	// consume podSyncStatuses[uid].pendingUpdate if set.
	podUpdates map[types.UID]chan struct{}
	// Tracks by UID the termination status of a pod - syncing, terminating,
	// terminated, and evicted.
	podSyncStatuses map[types.UID]*podSyncStatus

	// Tracks all uids for started static pods by full name
	startedStaticPodsByFullname map[string]types.UID
	// Tracks all uids for static pods that are waiting to start by full name
	waitingToStartStaticPodsByFullname map[string][]types.UID

	workQueue queue.WorkQueue

	// This function is run to sync the desired state of pod.
	// NOTE: This function has to be thread-safe - it can be called for
	// different pods at the same time.
	podSyncer podSyncer

	// workerChannelFn is exposed for testing to allow unit tests to impose delays
	// in channel communication. The function is invoked once each time a new worker
	// goroutine starts.
	workerChannelFn func(uid types.UID, in chan struct{}) (out <-chan struct{})

	// The EventRecorder to use
	recorder record.EventRecorder

	// backOffPeriod is the duration to back off when there is a sync error.
	backOffPeriod time.Duration

	// resyncInterval is the duration to wait until the next sync.
	resyncInterval time.Duration

	// podCache stores kubecontainer.PodStatus for all pods.
	podCache kubecontainer.Cache

	// clock is used for testing timing
	clock clock.PassiveClock
}

//这段代码定义了一个名为podWorkers的结构体,用于管理Pod的工作线程。
//它包含多个字段,用于保护和追踪每个工作线程的状态和操作,包括同步Pod的状态、管理静态Pod的启动和终止、处理Pod更新等。
//它还定义了一些回调函数和事件记录器,用于在同步Pod时执行特定操作和记录事件。

func newPodWorkers(
	podSyncer podSyncer,
	recorder record.EventRecorder,
	workQueue queue.WorkQueue,
	resyncInterval, backOffPeriod time.Duration,
	podCache kubecontainer.Cache,
) PodWorkers {
	return &podWorkers{
		podSyncStatuses:                    map[types.UID]*podSyncStatus{},
		podUpdates:                         map[types.UID]chan struct{}{},
		startedStaticPodsByFullname:        map[string]types.UID{},
		waitingToStartStaticPodsByFullname: map[string][]types.UID{},
		podSyncer:                          podSyncer,
		recorder:                           recorder,
		workQueue:                          workQueue,
		resyncInterval:                     resyncInterval,
		backOffPeriod:                      backOffPeriod,
		podCache:                           podCache,
		clock:                              clock.RealClock{},
	}
}

//该函数用于创建并初始化一个PodWorkers对象。
//PodWorkers是一个用于管理Pod同步状态和工作队列的结构体。
//函数接收多个参数,包括Pod同步器、事件记录器、工作队列、重同步间隔、退避周期、Pod缓存等。
//函数返回一个初始化后的PodWorkers对象。

func (p *podWorkers) IsPodKnownTerminated(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		return status.IsTerminated()
	}
	// if the pod is not known, we return false (pod worker is not aware of it)
	return false
}

//该函数用于判断指定的Pod是否已知终止状态。
//它通过锁定podWorkers的podLock,然后从podSyncStatuses中查找指定UID的Pod的同步状态。
//如果找到了该Pod的状态且其处于终止状态,则返回true;
//如果未找到该Pod或其状态不是终止状态,则返回false。

func (p *podWorkers) CouldHaveRunningContainers(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		return !status.IsTerminated()
	}
	// once all pods are synced, any pod without sync status is known to not be running.
	return !p.podsSynced
}

//该函数用于判断指定的Pod是否可能有正在运行的容器。
//它通过加锁获取Pod的同步状态,如果该Pod的状态存在且未终止,则返回true;
//如果所有Pod都已同步,且指定的Pod没有同步状态,则返回true;
//否则返回false。

func (p *podWorkers) ShouldPodBeFinished(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		return status.IsFinished()
	}
	// once all pods are synced, any pod without sync status is assumed to
	// have SyncTerminatedPod finished.
	return p.podsSynced
}

//该函数用于判断Pod是否应该被标记为完成。
//它通过锁定podWorkers结构体的锁,检查podSyncStatuses映射中是否存在给定UID的Pod的同步状态。
//如果存在且该状态表示Pod已完成,则函数返回true。
//如果不存在且所有Pod都已同步,则认为没有同步状态的任何Pod都已完成,并返回true。
//否则,返回false。

func (p *podWorkers) IsPodTerminationRequested(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		// the pod may still be setting up at this point.
		return status.IsTerminationRequested()
	}
	// an unknown pod is considered not to be terminating (use ShouldPodContainersBeTerminating in
	// cleanup loops to avoid failing to cleanup pods that have already been removed from config)
	return false
}

//该函数用于判断指定的Pod是否请求了终止。
//它通过锁定podSyncStatuses映射,检查给定的UID是否存在于映射中,
//如果存在则返回对应的status的IsTerminationRequested()方法的值,
//如果不存在则返回false。

func (p *podWorkers) ShouldPodContainersBeTerminating(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		// we wait until the pod worker goroutine observes the termination, which means syncPod will not
		// be executed again, which means no new containers can be started
		return status.IsTerminationStarted()
	}
	// once we've synced, if the pod isn't known to the workers we should be tearing them
	// down
	return p.podsSynced
}

//该函数用于判断Pod的容器是否应该终止。
//它通过锁定podWorkers结构体的锁,检查podSyncStatuses映射中是否存在给定的UID。
//如果存在,则调用IsTerminationStarted()方法检查是否已经开始终止,并返回结果。
//如果不存在,则返回podsSynced的值,表示是否应该终止Pod的容器。

func (p *podWorkers) ShouldPodRuntimeBeRemoved(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		return status.IsTerminated()
	}
	// a pod that hasn't been sent to the pod worker yet should have no runtime components once we have
	// synced all content.
	return p.podsSynced
}

//该函数用于判断Pod的运行时是否应该被移除。
//它通过加锁获取状态映射表podSyncStatuses中对应uid的Pod状态,如果状态存在且已终止,则返回true;
//如果不存在且所有内容已同步,则返回true。
//否则返回false。

func (p *podWorkers) ShouldPodContentBeRemoved(uid types.UID) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[uid]; ok {
		return status.IsEvicted() || (status.IsDeleted() && status.IsTerminated())
	}
	// a pod that hasn't been sent to the pod worker yet should have no content on disk once we have
	// synced all content.
	return p.podsSynced
}

//该函数用于判断Pod的内容是否应该被移除。
//它通过锁定podWorkers的锁,检查podSyncStatuses中是否存在给定的UID。
//如果存在,则判断Pod是否被驱逐或已删除且已终止。
//如果上述条件满足,则返回true,表示Pod的内容应该被移除。
//如果UID不存在podSyncStatuses中,则检查podsSynced标志是否为true,
//如果是,则表示所有内容已同步,Pod的内容应该被移除。最后返回判断结果。

func (p *podWorkers) IsPodForMirrorPodTerminatingByFullName(podFullName string) bool {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	uid, started := p.startedStaticPodsByFullname[podFullName]
	if !started {
		return false
	}
	status, exists := p.podSyncStatuses[uid]
	if !exists {
		return false
	}
	if !status.IsTerminationRequested() || status.IsTerminated() {
		return false
	}

	return true
}

//该函数用于判断指定的镜像Pod是否处于终止状态。
//它通过锁定podWorkers结构体的锁,然后根据pod的全名查找对应的UID和启动状态。
//如果Pod未启动,则返回false;
//然后根据UID查找Pod的同步状态。
//如果状态不存在,则返回false;
//接着判断Pod是否请求终止或已经终止,如果是则返回true,否则返回false。
//最后,释放锁。

func isPodStatusCacheTerminal(status *kubecontainer.PodStatus) bool {
	for _, container := range status.ContainerStatuses {
		if container.State == kubecontainer.ContainerStateRunning {
			return false
		}
	}
	for _, sb := range status.SandboxStatuses {
		if sb.State == runtimeapi.PodSandboxState_SANDBOX_READY {
			return false
		}
	}
	return true
}

//该函数用于判断Pod的状态缓存是否为终止状态。
//它遍历Pod的容器状态,如果发现有任何一个容器的状态为运行中,则返回false。然后,
//它遍历Pod的沙箱状态,如果发现有任何一个沙箱的状态为准备就绪,则返回false。
//如果所有的容器和沙箱状态都不是运行中或准备就绪,则返回true,表示Pod的状态缓存为终止状态。

// UpdatePod carries a configuration change or termination state to a pod. A pod is either runnable,
// terminating, or terminated, and will transition to terminating if: deleted on the apiserver,
// discovered to have a terminal phase (Succeeded or Failed), or evicted by the kubelet.
func (p *podWorkers) UpdatePod(options UpdatePodOptions) {
	// Handle when the pod is an orphan (no config) and we only have runtime status by running only
	// the terminating part of the lifecycle. A running pod contains only a minimal set of information
	// about the pod
	var isRuntimePod bool
	var uid types.UID
	var name, ns string
	if runningPod := options.RunningPod; runningPod != nil {
		if options.Pod == nil {
			// the sythetic pod created here is used only as a placeholder and not tracked
			if options.UpdateType != kubetypes.SyncPodKill {
				klog.InfoS("Pod update is ignored, runtime pods can only be killed", "pod", klog.KRef(runningPod.Namespace, runningPod.Name), "podUID", runningPod.ID, "updateType", options.UpdateType)
				return
			}
			uid, ns, name = runningPod.ID, runningPod.Namespace, runningPod.Name
			isRuntimePod = true
		} else {
			options.RunningPod = nil
			uid, ns, name = options.Pod.UID, options.Pod.Namespace, options.Pod.Name
			klog.InfoS("Pod update included RunningPod which is only valid when Pod is not specified", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
		}
	} else {
		uid, ns, name = options.Pod.UID, options.Pod.Namespace, options.Pod.Name
	}
	//该函数用于更新Pod的工作状态,包括配置变更或终止状态。
	//Pod有三种状态:可运行、终止中或已终止。当Pod被删除、发现处于终止状态(成功或失败)或被kubelet驱逐时,它将过渡到终止状态。
	//函数首先判断Pod是否为孤儿(无配置),如果是,则只运行生命周期的终止部分。
	//然后根据传入的UpdatePodOptions选项进行相应的处理,更新Pod的状态。

	p.podLock.Lock()
	defer p.podLock.Unlock()

	// decide what to do with this pod - we are either setting it up, tearing it down, or ignoring it
	var firstTime bool
	now := p.clock.Now()
	status, ok := p.podSyncStatuses[uid]
	if !ok {
		klog.V(4).InfoS("Pod is being synced for the first time", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
		firstTime = true
		status = &podSyncStatus{
			syncedAt: now,
			fullname: kubecontainer.BuildPodFullName(name, ns),
		}
		// if this pod is being synced for the first time, we need to make sure it is an active pod
		if options.Pod != nil && (options.Pod.Status.Phase == v1.PodFailed || options.Pod.Status.Phase == v1.PodSucceeded) {
			// Check to see if the pod is not running and the pod is terminal; if this succeeds then record in the podWorker that it is terminated.
			// This is needed because after a kubelet restart, we need to ensure terminal pods will NOT be considered active in Pod Admission. See http://issues.k8s.io/105523
			// However, `filterOutInactivePods`, considers pods that are actively terminating as active. As a result, `IsPodKnownTerminated()` needs to return true and thus `terminatedAt` needs to be set.
			if statusCache, err := p.podCache.Get(uid); err == nil {
				if isPodStatusCacheTerminal(statusCache) {
					// At this point we know:
					// (1) The pod is terminal based on the config source.
					// (2) The pod is terminal based on the runtime cache.
					// This implies that this pod had already completed `SyncTerminatingPod` sometime in the past. The pod is likely being synced for the first time due to a kubelet restart.
					// These pods need to complete SyncTerminatedPod to ensure that all resources are cleaned and that the status manager makes the final status updates for the pod.
					// As a result, set finished: false, to ensure a Terminated event will be sent and `SyncTerminatedPod` will run.
					status = &podSyncStatus{
						terminatedAt:       now,
						terminatingAt:      now,
						syncedAt:           now,
						startedTerminating: true,
						finished:           false,
						fullname:           kubecontainer.BuildPodFullName(name, ns),
					}
				}
			}
		}
		p.podSyncStatuses[uid] = status
	} //这段代码主要功能是决定如何处理一个Pod,包括设置、拆卸或忽略它。
	// 首先通过锁定podLock来保证并发安全,然后根据Pod的同步状态来决定对其进行何种操作。
	//如果Pod是首次同步,则将其状态设置为正在同步,并检查是否为活动Pod。
	//如果Pod已经终止,则将其状态设置为已终止。
	//最后,更新Pod的同步状态。

	// RunningPods represent an unknown pod execution and don't contain pod spec information
	// sufficient to perform any action other than termination. If we received a RunningPod
	// after a real pod has already been provided, use the most recent spec instead. Also,
	// once we observe a runtime pod we must drive it to completion, even if we weren't the
	// ones who started it.
	pod := options.Pod
	if isRuntimePod {
		status.observedRuntime = true
		switch {
		case status.pendingUpdate != nil && status.pendingUpdate.Pod != nil:
			pod = status.pendingUpdate.Pod
			options.Pod = pod
			options.RunningPod = nil
		case status.activeUpdate != nil && status.activeUpdate.Pod != nil:
			pod = status.activeUpdate.Pod
			options.Pod = pod
			options.RunningPod = nil
		default:
			// we will continue to use RunningPod.ToAPIPod() as pod here, but
			// options.Pod will be nil and other methods must handle that appropriately.
			pod = options.RunningPod.ToAPIPod()
		}
	}
	//这段Go代码中的函数片段是一个条件语句,用于根据isRuntimePod的值来更新pod变量的值。
	//如果isRuntimePod为true,则将status.observedRuntime标记为true,并根据status.pendingUpdate和status.activeUpdate的值来更新pod变量。
	//如果status.pendingUpdate不为nil且其Pod字段也不为nil,则将pod变量更新为status.pendingUpdate.Pod,并将options.Pod更新为pod,
	//同时将options.RunningPod设置为nil。如果status.activeUpdate不为nil且其Pod字段也不为nil,
	//则将pod变量更新为status.activeUpdate.Pod,并将options.Pod更新为pod,同时将options.RunningPod设置为nil。
	//如果以上条件都不满足,则将pod变量更新为options.RunningPod.ToAPIPod()的结果,但options.Pod将被设置为nil,
	//而其他方法需要适当地处理这种情况
	//。最后,将pod变量赋值给options.Pod。
	//这段代码的功能是在给定的options中更新pod的值,
	//根据isRuntimePod的值和status.pendingUpdate、status.activeUpdate的值来确定最终的pod值。

	// When we see a create update on an already terminating pod, that implies two pods with the same UID were created in
	// close temporal proximity (usually static pod but it's possible for an apiserver to extremely rarely do something
	// similar) - flag the sync status to indicate that after the pod terminates it should be reset to "not running" to
	// allow a subsequent add/update to start the pod worker again. This does not apply to the first time we see a pod,
	// such as when the kubelet restarts and we see already terminated pods for the first time.
	if !firstTime && status.IsTerminationRequested() {
		if options.UpdateType == kubetypes.SyncPodCreate {
			status.restartRequested = true
			klog.V(4).InfoS("Pod is terminating but has been requested to restart with same UID, will be reconciled later", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
			return
		}
	}
	//这段Go代码是一个条件判断语句,其功能是在特定条件下标记Pod的同步状态,以指示在Pod终止后应将其重置为“未运行”状态,
	//以便允许随后的添加/更新重新启动Pod工作器。
	//具体来说,函数首先检查是否是第一次看到这个Pod以及Pod是否已经请求终止。
	//如果满足这两个条件,并且更新类型是SyncPodCreate,则将标记Pod的restartRequested属性为true,并记录相关信息。

	// once a pod is terminated by UID, it cannot reenter the pod worker (until the UID is purged by housekeeping)
	if status.IsFinished() {
		klog.V(4).InfoS("Pod is finished processing, no further updates", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
		return
	}
	//该函数用于检查Pod的状态是否已完成。如果Pod已完成处理,则记录日志并退出函数。

	// check for a transition to terminating
	var becameTerminating bool
	if !status.IsTerminationRequested() {
		switch {
		case isRuntimePod:
			klog.V(4).InfoS("Pod is orphaned and must be torn down", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
			status.deleted = true
			status.terminatingAt = now
			becameTerminating = true
		case pod.DeletionTimestamp != nil:
			klog.V(4).InfoS("Pod is marked for graceful deletion, begin teardown", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
			status.deleted = true
			status.terminatingAt = now
			becameTerminating = true
		case pod.Status.Phase == v1.PodFailed, pod.Status.Phase == v1.PodSucceeded:
			klog.V(4).InfoS("Pod is in a terminal phase (success/failed), begin teardown", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
			status.terminatingAt = now
			becameTerminating = true
		case options.UpdateType == kubetypes.SyncPodKill:
			if options.KillPodOptions != nil && options.KillPodOptions.Evict {
				klog.V(4).InfoS("Pod is being evicted by the kubelet, begin teardown", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
				status.evicted = true
			} else {
				klog.V(4).InfoS("Pod is being removed by the kubelet, begin teardown", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
			}
			status.terminatingAt = now
			becameTerminating = true
		}
	}
	//该函数用于检查Pod是否进入终止状态。
	//根据Pod的不同条件,设置Pod的状态并记录日志。主要逻辑如下:
	//1. 如果Pod未请求终止,则根据以下条件判断Pod是否进入终止状态:
	//- 如果Pod是孤儿Pod,则将其标记为删除,并记录日志。
	//- 如果Pod已标记为优雅删除,则将其标记为删除,并记录日志。
	//- 如果Pod的状态为失败或成功,则记录日志。
	//- 如果Pod是由kubelet删除或驱逐,则记录相应的日志。
	//2. 设置Pod的终止时间,并记录是否变为终止状态。

	// once a pod is terminating, all updates are kills and the grace period can only decrease
	var wasGracePeriodShortened bool
	switch {
	case status.IsTerminated():
		// A terminated pod may still be waiting for cleanup - if we receive a runtime pod kill request
		// due to housekeeping seeing an older cached version of the runtime pod simply ignore it until
		// after the pod worker completes.
		if isRuntimePod {
			klog.V(3).InfoS("Pod is waiting for termination, ignoring runtime-only kill until after pod worker is fully terminated", "pod", klog.KRef(ns, name), "podUID", uid, "updateType", options.UpdateType)
			return
		}

		if options.KillPodOptions != nil {
			if ch := options.KillPodOptions.CompletedCh; ch != nil {
				close(ch)
			}
		}
		options.KillPodOptions = nil
		//该函数用于处理Pod终止状态的更新。主要逻辑如下:
		//1. 如果Pod已经终止,则根据以下条件处理:
		//- 如果是由于运行时Pod被杀死的请求,则忽略此次更新,直到Pod工作完成。
		//- 关闭KillPodOptions中的CompletedCh通道。
		//- 将KillPodOptions设置为nil。

	case status.IsTerminationRequested():
		if options.KillPodOptions == nil {
			options.KillPodOptions = &KillPodOptions{}
		}

		if ch := options.KillPodOptions.CompletedCh; ch != nil {
			status.notifyPostTerminating = append(status.notifyPostTerminating, ch)
		}
		if fn := options.KillPodOptions.PodStatusFunc; fn != nil {
			status.statusPostTerminating = append(status.statusPostTerminating, fn)
		}

		gracePeriod, gracePeriodShortened := calculateEffectiveGracePeriod(status, pod, options.KillPodOptions)

		wasGracePeriodShortened = gracePeriodShortened
		status.gracePeriod = gracePeriod
		// always set the grace period for syncTerminatingPod so we don't have to recalculate,
		// will never be zero.
		options.KillPodOptions.PodTerminationGracePeriodSecondsOverride = &gracePeriod

	default:
		// KillPodOptions is not valid for sync actions outside of the terminating phase
		if options.KillPodOptions != nil {
			if ch := options.KillPodOptions.CompletedCh; ch != nil {
				close(ch)
			}
			options.KillPodOptions = nil
		}
	}
	//这段Go代码是一个case语句的一部分,它根据status.IsTerminationRequested()的返回值执行不同的操作。
	//如果status的终止请求被触发,则执行以下操作:
	//1. 检查options.KillPodOptions是否为nil,如果是,则将其初始化为一个空的KillPodOptions对象。
	//2. 如果options.KillPodOptions.CompletedCh不为nil,则将其追加到status.notifyPostTerminating切片中。
	//3. 如果options.KillPodOptions.PodStatusFunc不为nil,则将其追加到status.statusPostTerminating切片中。
	//4. 调用calculateEffectiveGracePeriod函数计算有效的终止时间,并将结果赋值给gracePeriod和gracePeriodShortened。
	//5. 将gracePeriod赋值给status.gracePeriod,并将gracePeriod赋值给options.KillPodOptions.PodTerminationGracePeriodSecondsOverride,以便在syncTerminatingPod时不需要重新计算。
	//如果status.IsTerminationRequested()返回false,则执行以下操作:
	//1. 如果options.KillPodOptions不为nil,则关闭options.KillPodOptions.CompletedCh通道,并将options.KillPodOptions设置为nil。
	//这个代码段主要是处理Pod的终止请求,并根据不同的情况设置相应的选项和状态。

	// start the pod worker goroutine if it doesn't exist
	podUpdates, exists := p.podUpdates[uid]
	if !exists {
		// buffer the channel to avoid blocking this method
		podUpdates = make(chan struct{}, 1)
		p.podUpdates[uid] = podUpdates

		// ensure that static pods start in the order they are received by UpdatePod
		if kubetypes.IsStaticPod(pod) {
			p.waitingToStartStaticPodsByFullname[status.fullname] =
				append(p.waitingToStartStaticPodsByFullname[status.fullname], uid)
		}

		// allow testing of delays in the pod update channel
		var outCh <-chan struct{}
		if p.workerChannelFn != nil {
			outCh = p.workerChannelFn(uid, podUpdates)
		} else {
			outCh = podUpdates
		}

		// spawn a pod worker
		go func() {
			// TODO: this should be a wait.Until with backoff to handle panics, and
			// accept a context for shutdown
			defer runtime.HandleCrash()
			defer klog.V(3).InfoS("Pod worker has stopped", "podUID", uid)
			p.podWorkerLoop(uid, outCh)
		}()
	}
	//这段Go代码的功能是检查Pod的更新是否存在,如果不存在,则创建一个Pod更新的goroutine。
	//它首先检查p.podUpdates映射中是否存在给定UID的更新,如果不存在,则创建一个带缓冲的通道podUpdates,
	//将其添加到p.podUpdates映射中,并根据Pod的类型执行相应的操作。
	//如果Pod是静态Pod,则将其添加到waitingToStartStaticPodsByFullname映射中。
	//然后,根据提供的workerChannelFn函数选择一个通道来传递Pod更新。
	//最后,使用go关键字启动一个goroutine来执行podWorkerLoop函数。

	// measure the maximum latency between a call to UpdatePod and when the pod worker reacts to it
	// by preserving the oldest StartTime
	if status.pendingUpdate != nil && !status.pendingUpdate.StartTime.IsZero() && status.pendingUpdate.StartTime.Before(options.StartTime) {
		options.StartTime = status.pendingUpdate.StartTime
	}

	// notify the pod worker there is a pending update
	status.pendingUpdate = &options
	status.working = true
	klog.V(4).InfoS("Notifying pod of pending update", "pod", klog.KRef(ns, name), "podUID", uid, "workType", status.WorkType())
	select {
	case podUpdates <- struct{}{}:
	default:
	}

	if (becameTerminating || wasGracePeriodShortened) && status.cancelFn != nil {
		klog.V(3).InfoS("Cancelling current pod sync", "pod", klog.KRef(ns, name), "podUID", uid, "workType", status.WorkType())
		status.cancelFn()
		return
	}
}

//该函数用于更新Pod的状态,并通知Pod worker有一个待处理的更新。
//它首先检查是否有待处理的更新,并且更新的时间是否早于给定的开始时间,如果是,则将开始时间更新为待处理更新的时间。
//然后,它将待处理更新设置为当前选项,并标记为正在处理。
//接下来,它通过向podUpdates通道发送一个空结构体来通知Pod worker有更新。
//如果Pod的状态变为终止状态或者优雅关闭时间被缩短,并且存在取消函数,则会调用取消函数并返回。

// calculateEffectiveGracePeriod sets the initial grace period for a newly terminating pod or allows a
// shorter grace period to be provided, returning the desired value.
func calculateEffectiveGracePeriod(status *podSyncStatus, pod *v1.Pod, options *KillPodOptions) (int64, bool) {
	// enforce the restriction that a grace period can only decrease and track whatever our value is,
	// then ensure a calculated value is passed down to lower levels
	gracePeriod := status.gracePeriod
	// this value is bedrock truth - the apiserver owns telling us this value calculated by apiserver
	if override := pod.DeletionGracePeriodSeconds; override != nil {
		if gracePeriod == 0 || *override < gracePeriod {
			gracePeriod = *override
		}
	}
	// we allow other parts of the kubelet (namely eviction) to request this pod be terminated faster
	if options != nil {
		if override := options.PodTerminationGracePeriodSecondsOverride; override != nil {
			if gracePeriod == 0 || *override < gracePeriod {
				gracePeriod = *override
			}
		}
	}
	// make a best effort to default this value to the pod's desired intent, in the event
	// the kubelet provided no requested value (graceful termination?)
	if gracePeriod == 0 && pod.Spec.TerminationGracePeriodSeconds != nil {
		gracePeriod = *pod.Spec.TerminationGracePeriodSeconds
	}
	// no matter what, we always supply a grace period of 1
	if gracePeriod < 1 {
		gracePeriod = 1
	}
	return gracePeriod, status.gracePeriod != 0 && status.gracePeriod != gracePeriod
}

//该函数用于计算终止状态的Pod的优雅终止期限。
//它首先从Pod同步状态中获取初始优雅终止期限,然后根据Pod的删除期限和终止请求选项进行调整。
//如果Pod的删除期限小于当前期限,则使用Pod的删除期限。
//如果终止请求选项指定了更快的终止期限,则使用该期限。
//如果未指定终止期限,则使用Pod的规格中指定的终止期限。
//最后,如果计算得到的终止期限小于1,则将其设置为1。
//函数返回计算得到的终止期限和是否已更改终止期限的标志。

// allowPodStart tries to start the pod and returns true if allowed, otherwise
// it requeues the pod and returns false. If the pod will never be able to start
// because data is missing, or the pod was terminated before start, canEverStart
// is false. This method can only be called while holding the pod lock.
func (p *podWorkers) allowPodStart(pod *v1.Pod) (canStart bool, canEverStart bool) {
	if !kubetypes.IsStaticPod(pod) {
		// TODO: Do we want to allow non-static pods with the same full name?
		// Note that it may disable the force deletion of pods.
		return true, true
	}
	status, ok := p.podSyncStatuses[pod.UID]
	if !ok {
		klog.ErrorS(nil, "Pod sync status does not exist, the worker should not be running", "pod", klog.KObj(pod), "podUID", pod.UID)
		return false, false
	}
	if status.IsTerminationRequested() {
		return false, false
	}
	if !p.allowStaticPodStart(status.fullname, pod.UID) {
		p.workQueue.Enqueue(pod.UID, wait.Jitter(p.backOffPeriod, workerBackOffPeriodJitterFactor))
		return false, true
	}
	return true, true
}

//该函数是用于判断Pod是否可以启动的。
//函数首先判断Pod是否为静态Pod,如果不是,则直接返回true。
//如果是静态Pod,则根据Pod的同步状态来判断是否可以启动。
//如果Pod的同步状态不存在,则记录错误日志并返回false。
//如果Pod的同步状态请求终止,则返回false。
//如果允许静态Pod启动,则将Pod的UID加入工作队列并返回false,否则返回true。

// allowStaticPodStart tries to start the static pod and returns true if
// 1. there are no other started static pods with the same fullname
// 2. the uid matches that of the first valid static pod waiting to start
func (p *podWorkers) allowStaticPodStart(fullname string, uid types.UID) bool {
	startedUID, started := p.startedStaticPodsByFullname[fullname]
	if started {
		return startedUID == uid
	}

	waitingPods := p.waitingToStartStaticPodsByFullname[fullname]
	// TODO: This is O(N) with respect to the number of updates to static pods
	// with overlapping full names, and ideally would be O(1).
	for i, waitingUID := range waitingPods {
		// has pod already terminated or been deleted?
		status, ok := p.podSyncStatuses[waitingUID]
		if !ok || status.IsTerminationRequested() || status.IsTerminated() {
			continue
		}
		// another pod is next in line
		if waitingUID != uid {
			p.waitingToStartStaticPodsByFullname[fullname] = waitingPods[i:]
			return false
		}
		// we are up next, remove ourselves
		waitingPods = waitingPods[i+1:]
		break
	}
	if len(waitingPods) != 0 {
		p.waitingToStartStaticPodsByFullname[fullname] = waitingPods
	} else {
		delete(p.waitingToStartStaticPodsByFullname, fullname)
	}
	p.startedStaticPodsByFullname[fullname] = uid
	return true
}

//该函数是Go语言编写的,用于判断是否允许启动静态Pod。
//它接收两个参数:fullname(Pod的完整名称)和uid(Pod的唯一标识符)。
//函数返回一个布尔值,如果满足以下两个条件则返回true:
//1.没有其他已启动的具有相同完整名称的静态Pod;
//2.传入的uid与等待启动的第一个有效静态Pod的uid匹配。
//函数内部通过查询和遍历已启动的静态Pod和等待启动的静态Pod列表来判断是否允许启动。
//在遍历过程中,函数还会做一系列判断来确定下一个应该启动的Pod,并对等待启动的Pod列表进行相应的更新。
//最后,函数更新已启动的静态Pod列表,并返回结果。

// cleanupUnstartedPod is invoked if a pod that has never been started receives a termination
// signal before it can be started. This method must be called holding the pod lock.
func (p *podWorkers) cleanupUnstartedPod(pod *v1.Pod, status *podSyncStatus) {
	p.cleanupPodUpdates(pod.UID)

	if status.terminatingAt.IsZero() {
		klog.V(4).InfoS("Pod worker is complete but did not have terminatingAt set, likely programmer error", "pod", klog.KObj(pod), "podUID", pod.UID)
	}
	if !status.terminatedAt.IsZero() {
		klog.V(4).InfoS("Pod worker is complete and had terminatedAt set, likely programmer error", "pod", klog.KObj(pod), "podUID", pod.UID)
	}
	status.finished = true
	status.working = false
	status.terminatedAt = p.clock.Now()

	if p.startedStaticPodsByFullname[status.fullname] == pod.UID {
		delete(p.startedStaticPodsByFullname, status.fullname)
	}
}

//该函数是用于清理未启动的Pod的。
//如果一个Pod在启动前接到了终止信号,那么就会调用这个函数。
//函数内部会清理Pod的更新状态,并根据Pod的状态记录一些日志信息,并将Pod的状态标记为完成且终止。
//此外,如果该Pod是静态Pod,则会从已启动的静态Pod映射中删除该Pod。
//函数调用时需要持有Pod的锁。

// startPodSync is invoked by each pod worker goroutine when a message arrives on the pod update channel.
// This method consumes a pending update, initializes a context, decides whether the pod is already started
// or can be started, and updates the cached pod state so that downstream components can observe what the
// pod worker goroutine is currently attempting to do. If ok is false, there is no available event. If any
// of the boolean values is false, ensure the appropriate cleanup happens before returning.
//
// This method should ensure that either status.pendingUpdate is cleared and merged into status.activeUpdate,
// or when a pod cannot be started status.pendingUpdate remains the same. Pods that have not been started
// should never have an activeUpdate because that is exposed to downstream components on started pods.
func (p *podWorkers) startPodSync(podUID types.UID) (ctx context.Context, update podWork, canStart, canEverStart, ok bool) {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	//该函数是Go语言中的一个方法,名为startPodSync,它被每个Pod工作协程调用,当Pod更新通道上收到消息时。该方法的功能如下:
	//- 消费待处理的更新。
	//- 初始化一个上下文。
	//- 判断Pod是否已经启动或者可以启动。
	//- 更新缓存的Pod状态,以便下游组件可以观察到Pod工作协程当前正在尝试做什么。
	//该方法的返回值包括:
	//- ctx:上下文对象。
	//- update:Pod工作更新。
	//- canStart:是否可以启动Pod。
	//- canEverStart:是否可以永远启动Pod。
	//- ok:是否有可用事件。  该方法的执行过程如下:
	//1. 获取podLock锁。
	//2. 如果ok为false,表示没有可用事件,则直接返回。
	//3. 根据Pod的状态,决定是否可以启动Pod。
	//4. 更新缓存的Pod状态。
	//5. 释放podLock锁。
	//在执行过程中,该方法确保以下两点:  -
	//如果Pod无法启动,则保持status.pendingUpdate不变,并将其合并到status.activeUpdate中。
	//- 未启动的Pod不应有status.activeUpdate,因为这会被暴露给下游组件。
	//总之,该函数是一个用于同步Pod状态的函数,它被用于管理Pod的工作流程,并确保Pod状态的正确更新和同步。

	// verify we are known to the pod worker still
	status, ok := p.podSyncStatuses[podUID]
	if !ok {
		// pod status has disappeared, the worker should exit
		klog.V(4).InfoS("Pod worker no longer has status, worker should exit", "podUID", podUID)
		return nil, update, false, false, false
	}
	if !status.working {
		// working is used by unit tests to observe whether a worker is currently acting on this pod
		klog.V(4).InfoS("Pod should be marked as working by the pod worker, programmer error", "podUID", podUID)
	}
	if status.pendingUpdate == nil {
		// no update available, this means we were queued without work being added or there is a
		// race condition, both of which are unexpected
		status.working = false
		klog.V(4).InfoS("Pod worker received no pending work, programmer error?", "podUID", podUID)
		return nil, update, false, false, false
	}
	//该函数用于验证Pod是否仍然被pod worker所知。它首先通过podUID在podSyncStatuses中查找status,
	//如果找不到,则表示Pod状态已消失,worker应该退出。如果找到status,但status.working为false,则表示Pod未被标记为正在工作,
	//可能是程序员错误。
	//如果status.pendingUpdate为nil,则表示没有更新可用,这可能是由于未添加工作或存在竞态条件导致的,这两种情况都是意外的。
	//在这种情况下,将status.working设置为false,并返回相应的值。

	// consume the pending update
	update.WorkType = status.WorkType()
	update.Options = *status.pendingUpdate
	status.pendingUpdate = nil
	select {
	case <-p.podUpdates[podUID]:
		// ensure the pod update channel is empty (it is only ever written to under lock)
	default:
	}

	// initialize a context for the worker if one does not exist
	if status.ctx == nil || status.ctx.Err() == context.Canceled {
		status.ctx, status.cancelFn = context.WithCancel(context.Background())
	}
	ctx = status.ctx

	// if we are already started, make our state visible to downstream components
	if status.IsStarted() {
		status.mergeLastUpdate(update.Options)
		return ctx, update, true, true, true
	}

	// if we are already terminating and we only have a running pod, allow the worker
	// to "start" since we are immediately moving to terminating
	if update.Options.RunningPod != nil && update.WorkType == TerminatingPod {
		status.mergeLastUpdate(update.Options)
		return ctx, update, true, true, true
	}
	//该函数主要进行以下操作:
	//1. 将status.pendingUpdate的值赋给update.Options,并将status.pendingUpdate置为nil。
	//2. 使用select语句监听p.podUpdates[podUID]通道,如果没有消息则继续执行。
	//3. 如果status.ctx为空或者已经被取消,则创建一个新的上下文。
	//4. 如果工作状态已启动,则将最新更新合并到状态中,并返回上下文、更新和其他几个布尔值。
	//5. 如果工作状态为终止状态且只有一个运行中的Pod,则将最新更新合并到状态中,并返回上下文、更新和其他几个布尔值。
	//这个函数主要用于处理工作状态的更新,并根据当前状态进行相应的操作。

	// If we receive an update where Pod is nil (running pod is set) but haven't
	// started yet, we can only terminate the pod, not start it. We should not be
	// asked to start such a pod, but guard here just in case an accident occurs.
	if update.Options.Pod == nil {
		status.mergeLastUpdate(update.Options)
		klog.V(4).InfoS("Running pod cannot start ever, programmer error", "pod", klog.KObj(update.Options.Pod), "podUID", podUID, "updateType", update.WorkType)
		return ctx, update, false, false, true
	}

	// verify we can start
	canStart, canEverStart = p.allowPodStart(update.Options.Pod)
	switch {
	case !canEverStart:
		p.cleanupUnstartedPod(update.Options.Pod, status)
		status.working = false
		if start := update.Options.StartTime; !start.IsZero() {
			metrics.PodWorkerDuration.WithLabelValues("terminated").Observe(metrics.SinceInSeconds(start))
		}
		klog.V(4).InfoS("Pod cannot start ever", "pod", klog.KObj(update.Options.Pod), "podUID", podUID, "updateType", update.WorkType)
		return ctx, update, canStart, canEverStart, true
	case !canStart:
		// this is the only path we don't start the pod, so we need to put the change back in pendingUpdate
		status.pendingUpdate = &update.Options
		status.working = false
		klog.V(4).InfoS("Pod cannot start yet", "pod", klog.KObj(update.Options.Pod), "podUID", podUID)
		return ctx, update, canStart, canEverStart, true
	}

	// mark the pod as started
	status.startedAt = p.clock.Now()
	status.mergeLastUpdate(update.Options)

	// If we are admitting the pod and it is new, record the count of containers
	// TODO: We should probably move this into syncPod and add an execution count
	// to the syncPod arguments, and this should be recorded on the first sync.
	// Leaving it here complicates a particularly important loop.
	metrics.ContainersPerPodCount.Observe(float64(len(update.Options.Pod.Spec.Containers)))

	return ctx, update, true, true, true
}

//这段Go代码是一个处理Pod更新的函数。
//函数首先检查更新中的Pod是否为nil,如果是,则记录错误信息并返回。
//然后,函数通过调用p.allowPodStart来检查Pod是否可以启动。
//根据返回的结果,函数分别处理Pod不能启动或暂时不能启动的情况。
//最后,如果Pod可以启动,函数会记录启动时间并更新状态。
//- 函数首先检查update.Options.Pod是否为nil,如果是,则将最后更新的信息合并到status中,并记录日志信息,然后返回。
//- 接着,函数调用p.allowPodStart检查Pod是否可以启动,返回的结果存储在canStart和canEverStart变量中。
//- 如果canEverStart为false,表示Pod永远无法启动,函数会清理未启动的Pod,并记录相关指标和日志信息,然后返回。
//- 如果canStart为false但canEverStart为true,表示Pod暂时无法启动,函数将更新信息存回pendingUpdate中,并更新状态,然后记录日志信息并返回。
//- 如果Pod可以启动,函数会记录Pod的启动时间,并将最后更新的信息合并到status中。
//- 最后,函数记录Pod中容器的数量,并返回更新后的上下文、更新信息以及其他相关标志。

func podUIDAndRefForUpdate(update UpdatePodOptions) (types.UID, klog.ObjectRef) {
	if update.RunningPod != nil {
		return update.RunningPod.ID, klog.KObj(update.RunningPod.ToAPIPod())
	}
	return update.Pod.UID, klog.KObj(update.Pod)
}

//该函数根据传入的UpdatePodOptions结构体,返回Pod的UID和ObjectRef。
//- 如果update.RunningPod不为nil,则返回update.RunningPod.ID和klog.KObj(update.RunningPod.ToAPIPod())。
//- 否则,返回update.Pod.UID和klog.KObj(update.Pod)。

// podWorkerLoop manages sequential state updates to a pod in a goroutine, exiting once the final
// state is reached. The loop is responsible for driving the pod through four main phases:
//
// 1. Wait to start, guaranteeing no two pods with the same UID or same fullname are running at the same time
// 2. Sync, orchestrating pod setup by reconciling the desired pod spec with the runtime state of the pod
// 3. Terminating, ensuring all running containers in the pod are stopped
// 4. Terminated, cleaning up any resources that must be released before the pod can be deleted
//
// The podWorkerLoop is driven by updates delivered to UpdatePod and by SyncKnownPods. If a particular
// sync method fails, p.workerQueue is updated with backoff but it is the responsibility of the kubelet
// to trigger new UpdatePod calls. SyncKnownPods will only retry pods that are no longer known to the
// caller. When a pod transitions working->terminating or terminating->terminated, the next update is
// queued immediately and no kubelet action is required.
func (p *podWorkers) podWorkerLoop(podUID types.UID, podUpdates <-chan struct{}) {
	var lastSyncTime time.Time
	for range podUpdates {
		ctx, update, canStart, canEverStart, ok := p.startPodSync(podUID)
		// If we had no update waiting, it means someone initialized the channel without filling out pendingUpdate.
		if !ok {
			continue
		}
		// If the pod was terminated prior to the pod being allowed to start, we exit the loop.
		if !canEverStart {
			return
		}
		// If the pod is not yet ready to start, continue and wait for more updates.
		if !canStart {
			continue
		}
		//该函数是一个goroutine,用于管理Pod的顺序状态更新,直到达到最终状态才会退出。
		//该循环负责驱动Pod通过四个主要阶段:
		//1. 等待开始,保证不会有两个具有相同UID或相同全名的Pod同时运行。
		//2. 同步,通过协调期望的Pod规范与Pod的运行时状态来协调Pod的设置。
		//3. 终止,确保Pod中的所有运行容器都已停止。
		//4. 终止,清理必须在删除Pod之前释放的任何资源。
		//podWorkerLoop由UpdatePod传递的更新和SyncKnownPods驱动。
		//如果某个同步方法失败,则会更新p.workerQueue以进行退避,但由kubelet负责触发新的UpdatePod调用。
		//SyncKnownPods只会重试不再为调用者所知的Pod。
		//当Pod从working转换为terminating或terminating转换为terminated时,将立即排队进行下一个更新,并且不需要kubelet的操作。

		podUID, podRef := podUIDAndRefForUpdate(update.Options)

		klog.V(4).InfoS("Processing pod event", "pod", podRef, "podUID", podUID, "updateType", update.WorkType)
		var isTerminal bool
		err := func() error {
			// The worker is responsible for ensuring the sync method sees the appropriate
			// status updates on resyncs (the result of the last sync), transitions to
			// terminating (no wait), or on terminated (whatever the most recent state is).
			// Only syncing and terminating can generate pod status changes, while terminated
			// pods ensure the most recent status makes it to the api server.
			var status *kubecontainer.PodStatus
			var err error
			switch {
			case update.Options.RunningPod != nil:
				// when we receive a running pod, we don't need status at all because we are
				// guaranteed to be terminating and we skip updates to the pod
			default:
				// wait until we see the next refresh from the PLEG via the cache (max 2s)
				// TODO: this adds ~1s of latency on all transitions from sync to terminating
				//  to terminated, and on all termination retries (including evictions). We should
				//  improve latency by making the pleg continuous and by allowing pod status
				//  changes to be refreshed when key events happen (killPod, sync->terminating).
				//  Improving this latency also reduces the possibility that a terminated
				//  container's status is garbage collected before we have a chance to update the
				//  API server (thus losing the exit code).
				status, err = p.podCache.GetNewerThan(update.Options.Pod.UID, lastSyncTime)

				if err != nil {
					// This is the legacy event thrown by manage pod loop all other events are now dispatched
					// from syncPodFn
					p.recorder.Eventf(update.Options.Pod, v1.EventTypeWarning, events.FailedSync, "error determining status: %v", err)
					return err
				}
			}
			//这段Go代码是一个函数,用于处理Pod事件更新。
			//它根据传入的更新选项(update.Options),获取Pod的状态并进行相应的处理。具体步骤如下:
			//1. 根据更新选项,获取Pod的UID和引用(podUIDAndRefForUpdate函数)。
			//2. 使用klog记录日志,表示正在处理Pod事件。
			//3. 声明一个布尔变量isTerminal,用于判断Pod是否处于终止状态。
			//4. 在匿名函数中进行处理:
			//- 根据不同的情况,获取Pod的状态:
			//- 如果更新选项中的RunningPod不为nil,则不需要获取状态,因为此时Pod必定是要终止的,并且会跳过对Pod状态的更新。
			//- 否则,从podCache中获取比上次同步时间(lastSyncTime)更新的状态。如果获取失败,记录错误事件并返回错误。
			//- 如果获取到Pod状态,进行进一步处理。  这段代码的主要目的是确保在同步、终止和已终止状态下,Pod的状态能够正确更新并传递给API服务器。
			//在处理过程中,还会记录相应的日志信息和错误事件。

			// Take the appropriate action (illegal phases are prevented by UpdatePod)
			switch {
			case update.WorkType == TerminatedPod:
				err = p.podSyncer.SyncTerminatedPod(ctx, update.Options.Pod, status)

			case update.WorkType == TerminatingPod:
				var gracePeriod *int64
				if opt := update.Options.KillPodOptions; opt != nil {
					gracePeriod = opt.PodTerminationGracePeriodSecondsOverride
				}
				podStatusFn := p.acknowledgeTerminating(podUID)

				// if we only have a running pod, terminate it directly
				if update.Options.RunningPod != nil {
					err = p.podSyncer.SyncTerminatingRuntimePod(ctx, update.Options.RunningPod)
				} else {
					err = p.podSyncer.SyncTerminatingPod(ctx, update.Options.Pod, status, gracePeriod, podStatusFn)
				}

			default:
				isTerminal, err = p.podSyncer.SyncPod(ctx, update.Options.UpdateType, update.Options.Pod, update.Options.MirrorPod, status)
			}

			lastSyncTime = p.clock.Now()
			return err
		}()
		//这个go函数根据传入的update.WorkType采取相应的操作。
		//如果WorkType为TerminatedPod,则调用SyncTerminatedPod函数同步终止Pod。
		//如果WorkType为TerminatingPod,则根据条件分别调用SyncTerminatingRuntimePod或SyncTerminatingPod函数来同步终止运行中的Pod或终止Pod。
		//如果WorkType不是以上两种情况,则调用SyncPod函数来同步Pod。
		//最后更新lastSyncTime并返回可能的错误。

		var phaseTransition bool
		switch {
		case err == context.Canceled:
			// when the context is cancelled we expect an update to already be queued
			klog.V(2).InfoS("Sync exited with context cancellation error", "pod", podRef, "podUID", podUID, "updateType", update.WorkType)

		case err != nil:
			// we will queue a retry
			klog.ErrorS(err, "Error syncing pod, skipping", "pod", podRef, "podUID", podUID)

		case update.WorkType == TerminatedPod:
			// we can shut down the worker
			p.completeTerminated(podUID)
			if start := update.Options.StartTime; !start.IsZero() {
				metrics.PodWorkerDuration.WithLabelValues("terminated").Observe(metrics.SinceInSeconds(start))
			}
			klog.V(4).InfoS("Processing pod event done", "pod", podRef, "podUID", podUID, "updateType", update.WorkType)
			return

		case update.WorkType == TerminatingPod:
			// pods that don't exist in config don't need to be terminated, other loops will clean them up
			if update.Options.RunningPod != nil {
				p.completeTerminatingRuntimePod(podUID)
				if start := update.Options.StartTime; !start.IsZero() {
					metrics.PodWorkerDuration.WithLabelValues(update.Options.UpdateType.String()).Observe(metrics.SinceInSeconds(start))
				}
				klog.V(4).InfoS("Processing pod event done", "pod", podRef, "podUID", podUID, "updateType", update.WorkType)
				return
			}
			// otherwise we move to the terminating phase
			p.completeTerminating(podUID)
			phaseTransition = true

		case isTerminal:
			// if syncPod indicated we are now terminal, set the appropriate pod status to move to terminating
			klog.V(4).InfoS("Pod is terminal", "pod", podRef, "podUID", podUID, "updateType", update.WorkType)
			p.completeSync(podUID)
			phaseTransition = true
		}
		//该函数根据不同的条件执行不同的操作。
		//首先,如果err等于context.Canceled,则记录一条日志。
		//如果err不为nil,则记录错误日志并进行重试。如果update.WorkType等于TerminatedPod,则完成终止操作,并记录相关指标和日志。
		//如果update.WorkType等于TerminatingPod,则根据条件执行完成终止运行时Pod的操作或进行终止阶段的转换。
		//如果isTerminal为true,则设置Pod状态为终止,并进行终止阶段的转换。
		//最后,根据是否进行了终止阶段的转换,更新phaseTransition的值。

		// queue a retry if necessary, then put the next event in the channel if any
		p.completeWork(podUID, phaseTransition, err)
		if start := update.Options.StartTime; !start.IsZero() {
			metrics.PodWorkerDuration.WithLabelValues(update.Options.UpdateType.String()).Observe(metrics.SinceInSeconds(start))
		}
		klog.V(4).InfoS("Processing pod event done", "pod", podRef, "podUID", podUID, "updateType", update.WorkType)
	} //该函数主要完成以下功能:
	// 1. 根据需要对pod进行重试,并将下一个事件放入通道中。
	//2. 如果有启动时间,则记录pod工作持续时间的指标。
	//3. 打印日志信息,表示pod事件处理完成。
	//具体描述如下:
	//- p.completeWork(podUID, phaseTransition, err) 完成工作,根据需要进行重试,并将下一个事件放入通道中。
	//- if start := update.Options.StartTime; !start.IsZero() { metrics.PodWorkerDuration.WithLabelValues(update.Options.UpdateType.String()).Observe(metrics.SinceInSeconds(start)) }
	//如果有启动时间,则记录pod工作持续时间的指标,使用metrics.SinceInSeconds(start)计算自启动时间以来的时间。
	//- klog.V(4).InfoS("Processing pod event done", "pod", podRef, "podUID", podUID, "updateType", update.WorkType) 打印日志信息,
	//表示pod事件处理完成,包括pod的引用、UID、更新类型等信息。

}

// acknowledgeTerminating sets the terminating flag on the pod status once the pod worker sees
// the termination state so that other components know no new containers will be started in this
// pod. It then returns the status function, if any, that applies to this pod.
func (p *podWorkers) acknowledgeTerminating(podUID types.UID) PodStatusFunc {
	p.podLock.Lock()
	defer p.podLock.Unlock()

	status, ok := p.podSyncStatuses[podUID]
	if !ok {
		return nil
	}

	if !status.terminatingAt.IsZero() && !status.startedTerminating {
		klog.V(4).InfoS("Pod worker has observed request to terminate", "podUID", podUID)
		status.startedTerminating = true
	}

	if l := len(status.statusPostTerminating); l > 0 {
		return status.statusPostTerminating[l-1]
	}
	return nil
}

//该函数是podWorkers结构体的一个方法,用于设置Pod的终止状态标志,并返回适用于该Pod的状态函数。
//具体功能如下:
//1. 加锁并defer解锁,保证并发安全。
//2. 判断Pod的同步状态是否存在,若不存在则返回nil。
//3. 若Pod的终止时间已设置且未开始终止,则设置开始终止状态,并打印日志信息。
//4. 若存在适用于终止状态后的状态函数,则返回最后一个状态函数;否则返回nil。

// completeSync is invoked when syncPod completes successfully and indicates the pod is now terminal and should
// be terminated. This happens when the natural pod lifecycle completes - any pod which is not RestartAlways
// exits. Unnatural completions, such as evictions, API driven deletion or phase transition, are handled by
// UpdatePod.
func (p *podWorkers) completeSync(podUID types.UID) {
	p.podLock.Lock()
	defer p.podLock.Unlock()

	klog.V(4).InfoS("Pod indicated lifecycle completed naturally and should now terminate", "podUID", podUID)

	status, ok := p.podSyncStatuses[podUID]
	if !ok {
		klog.V(4).InfoS("Pod had no status in completeSync, programmer error?", "podUID", podUID)
		return
	}

	// update the status of the pod
	if status.terminatingAt.IsZero() {
		status.terminatingAt = p.clock.Now()
	} else {
		klog.V(4).InfoS("Pod worker attempted to set terminatingAt twice, likely programmer error", "podUID", podUID)
	}
	status.startedTerminating = true

	// the pod has now transitioned to terminating and we want to run syncTerminatingPod
	// as soon as possible, so if no update is already waiting queue a synthetic update
	p.requeueLastPodUpdate(podUID, status)
}

//该函数是podWorkers结构体的一个方法,用于在同步Pod成功完成且Pod处于终止状态时调用。
//它主要完成以下几个功能:
//1. 加锁并defer解锁,保证并发安全。
//2. 打印日志信息,表示Pod生命周期自然完成并即将终止。
//3. 判断Pod的同步状态是否存在,若不存在则打印日志并返回。
//4. 若Pod未设置终止时间,则设置终止时间为当前时间;若已设置终止时间,则打印错误日志。
//5. 设置Pod开始终止状态。
//6. 调用requeueLastPodUpdate方法,重新排队等待同步终止状态的Pod。

// completeTerminating is invoked when syncTerminatingPod completes successfully, which means
// no container is running, no container will be started in the future, and we are ready for
// cleanup.  This updates the termination state which prevents future syncs and will ensure
// other kubelet loops know this pod is not running any containers.
func (p *podWorkers) completeTerminating(podUID types.UID) {
	p.podLock.Lock()
	defer p.podLock.Unlock()

	klog.V(4).InfoS("Pod terminated all containers successfully", "podUID", podUID)

	status, ok := p.podSyncStatuses[podUID]
	if !ok {
		return
	}

	// update the status of the pod
	if status.terminatingAt.IsZero() {
		klog.V(4).InfoS("Pod worker was terminated but did not have terminatingAt set, likely programmer error", "podUID", podUID)
	}
	status.terminatedAt = p.clock.Now()
	for _, ch := range status.notifyPostTerminating {
		close(ch)
	}
	status.notifyPostTerminating = nil
	status.statusPostTerminating = nil

	// the pod has now transitioned to terminated and we want to run syncTerminatedPod
	// as soon as possible, so if no update is already waiting queue a synthetic update
	p.requeueLastPodUpdate(podUID, status)
}

//该函数的作用是当syncTerminatingPod成功完成时,更新Pod的终止状态,以防止未来的同步,并确保其他kubelet循环知道此Pod未运行任何容器。
//函数首先锁定podLock,然后获取podSyncStatuses中对应podUID的状态。
//如果状态不存在,则直接返回。
//然后更新Pod的状态,如果terminatingAt为零值,则记录日志信息。
//设置terminatedAt为当前时间,并关闭所有notifyPostTerminating通道,并清空相关状态。
//最后,如果未等待更新,则排队一个合成更新,以尽快运行syncTerminatedPod。

// completeTerminatingRuntimePod is invoked when syncTerminatingPod completes successfully,
// which means an orphaned pod (no config) is terminated and we can exit. Since orphaned
// pods have no API representation, we want to exit the loop at this point and ensure no
// status is present afterwards - the running pod is truly terminated when this is invoked.
func (p *podWorkers) completeTerminatingRuntimePod(podUID types.UID) {
	p.podLock.Lock()
	defer p.podLock.Unlock()

	klog.V(4).InfoS("Pod terminated all orphaned containers successfully and worker can now stop", "podUID", podUID)

	p.cleanupPodUpdates(podUID)

	status, ok := p.podSyncStatuses[podUID]
	if !ok {
		return
	}
	if status.terminatingAt.IsZero() {
		klog.V(4).InfoS("Pod worker was terminated but did not have terminatingAt set, likely programmer error", "podUID", podUID)
	}
	status.terminatedAt = p.clock.Now()
	status.finished = true
	status.working = false

	if p.startedStaticPodsByFullname[status.fullname] == podUID {
		delete(p.startedStaticPodsByFullname, status.fullname)
	}

	// A runtime pod is transient and not part of the desired state - once it has reached
	// terminated we can abandon tracking it.
	delete(p.podSyncStatuses, podUID)
}

//该函数是Go语言编写的,用于在同步终止Pod完成成功时调用,即终止了一个孤立的Pod(没有配置)并且可以退出循环。
//因为孤立的Pod没有API表示,所以在此时调用该函数可以确保之后没有状态存在
//- 运行中的Pod真正终止了。  函数详细说明:
//- 首先通过锁定podLock来确保并发安全;
//- 打印日志信息,表示Pod成功终止了所有孤立的容器,现在可以停止工作;
//- 调用cleanupPodUpdates函数来清理Pod更新;
//- 从podSyncStatuses中获取Pod的状态,如果不存在则直接返回;
//- 检查terminatingAt是否为零值,如果是则打印日志信息,表示Pod的工作线程被终止了,但是terminatingAt没有被设置,这可能是一个编程错误;
//- 设置terminatedAt为当前时间,标记finished和working为true,表示Pod已经终止;
//- 如果startedStaticPodsByFullname中使用fullname索引的Pod是当前Pod,则从map中删除该Pod;
//- 最后,从podSyncStatuses中删除该Pod的状态。
//通过以上操作,该函数完成了对终止的运行时Pod的处理,并停止了对它的跟踪。

// completeTerminated is invoked after syncTerminatedPod completes successfully and means we
// can stop the pod worker. The pod is finalized at this point.
func (p *podWorkers) completeTerminated(podUID types.UID) {
	p.podLock.Lock()
	defer p.podLock.Unlock()

	klog.V(4).InfoS("Pod is complete and the worker can now stop", "podUID", podUID)

	p.cleanupPodUpdates(podUID)

	status, ok := p.podSyncStatuses[podUID]
	if !ok {
		return
	}
	if status.terminatingAt.IsZero() {
		klog.V(4).InfoS("Pod worker is complete but did not have terminatingAt set, likely programmer error", "podUID", podUID)
	}
	if status.terminatedAt.IsZero() {
		klog.V(4).InfoS("Pod worker is complete but did not have terminatedAt set, likely programmer error", "podUID", podUID)
	}
	status.finished = true
	status.working = false

	if p.startedStaticPodsByFullname[status.fullname] == podUID {
		delete(p.startedStaticPodsByFullname, status.fullname)
	}
}

//该函数是podWorkers结构体的一个方法,用于标记指定pod的worker已完成,并进行一些清理工作。
//函数首先通过锁定pod锁来确保并发安全,然后记录日志表示pod已完成,并调用cleanupPodUpdates方法进行清理操作。
//接着,函数检查pod的同步状态,如果状态不存在则直接返回。
//如果pod的terminatingAt和terminatedAt时间都未设置,函数会记录警告日志。
//最后,函数更新pod的同步状态为完成,并删除静态pod的映射关系。

// completeWork requeues on error or the next sync interval and then immediately executes any pending
// work.
func (p *podWorkers) completeWork(podUID types.UID, phaseTransition bool, syncErr error) {
	// Requeue the last update if the last sync returned error.
	switch {
	case phaseTransition:
		p.workQueue.Enqueue(podUID, 0)
	case syncErr == nil:
		// No error; requeue at the regular resync interval.
		p.workQueue.Enqueue(podUID, wait.Jitter(p.resyncInterval, workerResyncIntervalJitterFactor))
	case strings.Contains(syncErr.Error(), NetworkNotReadyErrorMsg):
		// Network is not ready; back off for short period of time and retry as network might be ready soon.
		p.workQueue.Enqueue(podUID, wait.Jitter(backOffOnTransientErrorPeriod, workerBackOffPeriodJitterFactor))
	default:
		// Error occurred during the sync; back off and then retry.
		p.workQueue.Enqueue(podUID, wait.Jitter(p.backOffPeriod, workerBackOffPeriodJitterFactor))
	}

	// if there is a pending update for this worker, requeue immediately, otherwise
	// clear working status
	p.podLock.Lock()
	defer p.podLock.Unlock()
	if status, ok := p.podSyncStatuses[podUID]; ok {
		if status.pendingUpdate != nil {
			select {
			case p.podUpdates[podUID] <- struct{}{}:
				klog.V(4).InfoS("Requeueing pod due to pending update", "podUID", podUID)
			default:
				klog.V(4).InfoS("Pending update already queued", "podUID", podUID)
			}
		} else {
			status.working = false
		}
	}
}

//该函数主要用于处理Pod的工作完成。根据传入的参数,它会在错误或下一个同步间隔时重新排队,并立即执行任何待处理的工作。
//具体来说,根据phaseTransition、syncErr的不同情况,将重新排队的时间间隔进行调整。
//同时,函数还会检查是否有待处理的更新,并根据情况进行重新排队或清除工作状态。

// SyncKnownPods will purge any fully terminated pods that are not in the desiredPods
// list, which means SyncKnownPods must be called in a threadsafe manner from calls
// to UpdatePods for new pods. Because the podworker is dependent on UpdatePod being
// invoked to drive a pod's state machine, if a pod is missing in the desired list the
// pod worker must be responsible for delivering that update. The method returns a map
// of known workers that are not finished with a value of SyncPodTerminated,
// SyncPodKill, or SyncPodSync depending on whether the pod is terminated, terminating,
// or syncing.
func (p *podWorkers) SyncKnownPods(desiredPods []*v1.Pod) map[types.UID]PodWorkerSync {
	workers := make(map[types.UID]PodWorkerSync)
	known := make(map[types.UID]struct{})
	for _, pod := range desiredPods {
		known[pod.UID] = struct{}{}
	}

	p.podLock.Lock()
	defer p.podLock.Unlock()

	p.podsSynced = true
	for uid, status := range p.podSyncStatuses {
		// We retain the worker history of any pod that is still desired according to
		// its UID. However, there are two scenarios during a sync that result in us
		// needing to purge the history:
		//
		// 1. The pod is no longer desired (the local version is orphaned)
		// 2. The pod received a kill update and then a subsequent create, which means
		//    the UID was reused in the source config (vanishingly rare for API servers,
		//    common for static pods that have specified a fixed UID)
		//
		// In the former case we wish to bound the amount of information we store for
		// deleted pods. In the latter case we wish to minimize the amount of time before
		// we restart the static pod. If we succeed at removing the worker, then we
		// omit it from the returned map of known workers, and the caller of SyncKnownPods
		// is expected to send a new UpdatePod({UpdateType: Create}).
		_, knownPod := known[uid]
		orphan := !knownPod
		if status.restartRequested || orphan {
			if p.removeTerminatedWorker(uid, status, orphan) {
				// no worker running, we won't return it
				continue
			}
		}

		sync := PodWorkerSync{
			State:  status.WorkType(),
			Orphan: orphan,
		}
		switch {
		case status.activeUpdate != nil:
			if status.activeUpdate.Pod != nil {
				sync.HasConfig = true
				sync.Static = kubetypes.IsStaticPod(status.activeUpdate.Pod)
			}
		case status.pendingUpdate != nil:
			if status.pendingUpdate.Pod != nil {
				sync.HasConfig = true
				sync.Static = kubetypes.IsStaticPod(status.pendingUpdate.Pod)
			}
		}
		workers[uid] = sync
	}
	return workers
}

//该函数用于同步已知的Pods,它会清除不在所需Pods列表中的完全终止的Pods。
//函数需要以线程安全的方式从更新Pods的调用中调用。
//函数返回一个映射,该映射包含未完成的PodWorker的状态,状态分为SyncPodTerminated、SyncPodKill和SyncPodSync。
//函数首先根据所需Pods列表创建一个known映射,然后锁定podLock,并遍历podSyncStatuses,根据Pod的UID保留其工作历史。
//如果Pod不再被需要或已经终止,则从podSyncStatuses中移除该Pod,并在返回的映射中忽略它。
//否则,根据Pod的状态,将PodWorker的状态添加到返回的映射中。

// removeTerminatedWorker cleans up and removes the worker status for a worker
// that has reached a terminal state of "finished" - has successfully exited
// syncTerminatedPod. This "forgets" a pod by UID and allows another pod to be
// recreated with the same UID. The kubelet preserves state about recently
// terminated pods to prevent accidentally restarting a terminal pod, which is
// proportional to the number of pods described in the pod config. The method
// returns true if the worker was completely removed.
func (p *podWorkers) removeTerminatedWorker(uid types.UID, status *podSyncStatus, orphaned bool) bool {
	if !status.finished {
		// If the pod worker has not reached terminal state and the pod is still known, we wait.
		if !orphaned {
			klog.V(4).InfoS("Pod worker has been requested for removal but is still not fully terminated", "podUID", uid)
			return false
		}

		// all orphaned pods are considered deleted
		status.deleted = true

		// When a pod is no longer in the desired set, the pod is considered orphaned and the
		// the pod worker becomes responsible for driving the pod to completion (there is no
		// guarantee another component will notify us of updates).
		switch {
		case !status.IsStarted() && !status.observedRuntime:
			// The pod has not been started, which means we can safely clean up the pod - the
			// pod worker will shutdown as a result of this change without executing a sync.
			klog.V(4).InfoS("Pod is orphaned and has not been started", "podUID", uid)
		case !status.IsTerminationRequested():
			// The pod has been started but termination has not been requested - set the appropriate
			// timestamp and notify the pod worker. Because the pod has been synced at least once,
			// the value of status.activeUpdate will be the fallback for the next sync.
			status.terminatingAt = p.clock.Now()
			if status.activeUpdate != nil && status.activeUpdate.Pod != nil {
				status.gracePeriod, _ = calculateEffectiveGracePeriod(status, status.activeUpdate.Pod, nil)
			} else {
				status.gracePeriod = 1
			}
			p.requeueLastPodUpdate(uid, status)
			klog.V(4).InfoS("Pod is orphaned and still running, began terminating", "podUID", uid)
			return false
		default:
			// The pod is already moving towards termination, notify the pod worker. Because the pod
			// has been synced at least once, the value of status.activeUpdate will be the fallback for
			// the next sync.
			p.requeueLastPodUpdate(uid, status)
			klog.V(4).InfoS("Pod is orphaned and still terminating, notified the pod worker", "podUID", uid)
			return false
		}
	}

	if status.restartRequested {
		klog.V(4).InfoS("Pod has been terminated but another pod with the same UID was created, remove history to allow restart", "podUID", uid)
	} else {
		klog.V(4).InfoS("Pod has been terminated and is no longer known to the kubelet, remove all history", "podUID", uid)
	}
	delete(p.podSyncStatuses, uid)
	p.cleanupPodUpdates(uid)

	if p.startedStaticPodsByFullname[status.fullname] == uid {
		delete(p.startedStaticPodsByFullname, status.fullname)
	}
	return true
}

//该函数用于清理并移除已达到终止状态“finished”的worker的工作状态。
//如果worker已成功退出同步终止Pod,则将其状态“忘记”,并允许使用相同的UID创建另一个Pod。
//该函数返回一个布尔值,表示是否成功完全移除了worker。
//- 首先,检查worker是否已达到终止状态。如果未达到终止状态且pod仍被知道,则等待。
//- 如果pod已被遗弃,则将pod标记为已删除,并根据pod的状态执行相应的操作。
//- 如果pod未开始运行且未观察到运行时状态,则安全地清理pod,并关闭pod worker。
//- 如果已开始运行但未请求终止,则设置适当的终止时间戳并通知pod worker。
//- 如果pod已请求终止,则通知pod worker。
//- 最后,如果worker已达到终止状态,则根据是否请求重新启动pod执行相应的操作,并删除相关状态和更新,并从已启动的静态Pod映射中移除UID,
//然后返回true表示成功移除worker。

// killPodNow returns a KillPodFunc that can be used to kill a pod.
// It is intended to be injected into other modules that need to kill a pod.
func killPodNow(podWorkers PodWorkers, recorder record.EventRecorder) eviction.KillPodFunc {
	return func(pod *v1.Pod, isEvicted bool, gracePeriodOverride *int64, statusFn func(*v1.PodStatus)) error {
		// determine the grace period to use when killing the pod
		gracePeriod := int64(0)
		if gracePeriodOverride != nil {
			gracePeriod = *gracePeriodOverride
		} else if pod.Spec.TerminationGracePeriodSeconds != nil {
			gracePeriod = *pod.Spec.TerminationGracePeriodSeconds
		}

		// we timeout and return an error if we don't get a callback within a reasonable time.
		// the default timeout is relative to the grace period (we settle on 10s to wait for kubelet->runtime traffic to complete in sigkill)
		timeout := gracePeriod + (gracePeriod / 2)
		minTimeout := int64(10)
		if timeout < minTimeout {
			timeout = minTimeout
		}
		timeoutDuration := time.Duration(timeout) * time.Second

		// open a channel we block against until we get a result
		ch := make(chan struct{}, 1)
		podWorkers.UpdatePod(UpdatePodOptions{
			Pod:        pod,
			UpdateType: kubetypes.SyncPodKill,
			KillPodOptions: &KillPodOptions{
				CompletedCh:                              ch,
				Evict:                                    isEvicted,
				PodStatusFunc:                            statusFn,
				PodTerminationGracePeriodSecondsOverride: gracePeriodOverride,
			},
		})

		// wait for either a response, or a timeout
		select {
		case <-ch:
			return nil
		case <-time.After(timeoutDuration):
			recorder.Eventf(pod, v1.EventTypeWarning, events.ExceededGracePeriod, "Container runtime did not kill the pod within specified grace period.")
			return fmt.Errorf("timeout waiting to kill pod")
		}
	}
}

//该函数killPodNow返回一个KillPodFunc类型的函数,可以用于杀死一个Pod。
//其设计目的是被注入到其他需要杀死Pod的模块中。  详细说明:
//1. 函数接受两个参数:podWorkers和recorder,分别用于更新Pod状态和记录事件。
//2. 返回的函数接受四个参数:pod表示要杀死的Pod,isEvicted表示是否被驱逐,gracePeriodOverride表示覆盖的优雅终止期限,
//statusFn表示获取Pod状态的函数。
//3. 确定杀死Pod时使用的优雅终止期限,优先使用gracePeriodOverride,如果为空,则使用pod.Spec.TerminationGracePeriodSeconds。
//4. 计算等待回调的超时时间,默认为优雅终止期限的一半,但不会少于10秒。
//5. 使用podWorkers.UpdatePod更新Pod状态,包括设置完成通道、是否被驱逐、获取Pod状态的函数和覆盖的优雅终止期限。
//6. 阻塞等待完成通道的消息或超时时间,如果收到完成通道的消息,则返回nil,否则记录事件并返回超时错误。

// cleanupPodUpdates closes the podUpdates channel and removes it from
// podUpdates map so that the corresponding pod worker can stop. It also
// removes any undelivered work. This method must be called holding the
// pod lock.
func (p *podWorkers) cleanupPodUpdates(uid types.UID) {
	if ch, ok := p.podUpdates[uid]; ok {
		close(ch)
	}
	delete(p.podUpdates, uid)
}

//该函数用于清理pod更新。
//它关闭指定pod的更新通道,并从pod更新映射中移除该通道,以便相应的pod工作线程可以停止。
//同时,它还会移除任何未传递的工作。
//此方法必须在持有pod锁时调用。

// requeueLastPodUpdate creates a new pending pod update from the most recently
// executed update if no update is already queued, and then notifies the pod
// worker goroutine of the update. This method must be called while holding
// the pod lock.
func (p *podWorkers) requeueLastPodUpdate(podUID types.UID, status *podSyncStatus) {
	// if there is already an update queued, we can use that instead, or if
	// we have no previously executed update, we cannot replay it.
	if status.pendingUpdate != nil || status.activeUpdate == nil {
		return
	}
	copied := *status.activeUpdate
	status.pendingUpdate = &copied

	// notify the pod worker
	status.working = true
	select {
	case p.podUpdates[podUID] <- struct{}{}:
	default:
	}
}

//该函数用于将最近一次执行的更新重新排队为待处理的Pod更新,并通知Pod工作协程进行更新。
//函数需要在持有Pod锁的情况下调用。具体实现如下:
//1. 如果已经有一个更新排队,或者没有先前执行的更新,则直接返回。
//2. 否则,将最近一次执行的更新复制到pendingUpdate中。
//3. 通知Pod工作协程,将working设置为true。
//4. 尝试向podUpdates通道发送一个空结构体,如果通道已满,则直接退出。