status_manager.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package status
  14. import (
  15. "fmt"
  16. "sort"
  17. "sync"
  18. "time"
  19. clientset "k8s.io/client-go/kubernetes"
  20. "k8s.io/api/core/v1"
  21. apiequality "k8s.io/apimachinery/pkg/api/equality"
  22. "k8s.io/apimachinery/pkg/api/errors"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/types"
  25. "k8s.io/apimachinery/pkg/util/diff"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. "k8s.io/klog"
  28. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  29. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  30. kubepod "k8s.io/kubernetes/pkg/kubelet/pod"
  31. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  32. "k8s.io/kubernetes/pkg/kubelet/util/format"
  33. statusutil "k8s.io/kubernetes/pkg/util/pod"
  34. )
  35. // A wrapper around v1.PodStatus that includes a version to enforce that stale pod statuses are
  36. // not sent to the API server.
  37. type versionedPodStatus struct {
  38. status v1.PodStatus
  39. // Monotonically increasing version number (per pod).
  40. version uint64
  41. // Pod name & namespace, for sending updates to API server.
  42. podName string
  43. podNamespace string
  44. }
  45. type podStatusSyncRequest struct {
  46. podUID types.UID
  47. status versionedPodStatus
  48. }
  49. // Updates pod statuses in apiserver. Writes only when new status has changed.
  50. // All methods are thread-safe.
  51. type manager struct {
  52. kubeClient clientset.Interface
  53. podManager kubepod.Manager
  54. // Map from pod UID to sync status of the corresponding pod.
  55. podStatuses map[types.UID]versionedPodStatus
  56. podStatusesLock sync.RWMutex
  57. podStatusChannel chan podStatusSyncRequest
  58. // Map from (mirror) pod UID to latest status version successfully sent to the API server.
  59. // apiStatusVersions must only be accessed from the sync thread.
  60. apiStatusVersions map[kubetypes.MirrorPodUID]uint64
  61. podDeletionSafety PodDeletionSafetyProvider
  62. }
  63. // PodStatusProvider knows how to provide status for a pod. It's intended to be used by other components
  64. // that need to introspect status.
  65. type PodStatusProvider interface {
  66. // GetPodStatus returns the cached status for the provided pod UID, as well as whether it
  67. // was a cache hit.
  68. GetPodStatus(uid types.UID) (v1.PodStatus, bool)
  69. }
  70. // An object which provides guarantees that a pod can be safely deleted.
  71. type PodDeletionSafetyProvider interface {
  72. // A function which returns true if the pod can safely be deleted
  73. PodResourcesAreReclaimed(pod *v1.Pod, status v1.PodStatus) bool
  74. }
  75. // Manager is the Source of truth for kubelet pod status, and should be kept up-to-date with
  76. // the latest v1.PodStatus. It also syncs updates back to the API server.
  77. type Manager interface {
  78. PodStatusProvider
  79. // Start the API server status sync loop.
  80. Start()
  81. // SetPodStatus caches updates the cached status for the given pod, and triggers a status update.
  82. SetPodStatus(pod *v1.Pod, status v1.PodStatus)
  83. // SetContainerReadiness updates the cached container status with the given readiness, and
  84. // triggers a status update.
  85. SetContainerReadiness(podUID types.UID, containerID kubecontainer.ContainerID, ready bool)
  86. // TerminatePod resets the container status for the provided pod to terminated and triggers
  87. // a status update.
  88. TerminatePod(pod *v1.Pod)
  89. // RemoveOrphanedStatuses scans the status cache and removes any entries for pods not included in
  90. // the provided podUIDs.
  91. RemoveOrphanedStatuses(podUIDs map[types.UID]bool)
  92. }
  93. const syncPeriod = 10 * time.Second
  94. func NewManager(kubeClient clientset.Interface, podManager kubepod.Manager, podDeletionSafety PodDeletionSafetyProvider) Manager {
  95. return &manager{
  96. kubeClient: kubeClient,
  97. podManager: podManager,
  98. podStatuses: make(map[types.UID]versionedPodStatus),
  99. podStatusChannel: make(chan podStatusSyncRequest, 1000), // Buffer up to 1000 statuses
  100. apiStatusVersions: make(map[kubetypes.MirrorPodUID]uint64),
  101. podDeletionSafety: podDeletionSafety,
  102. }
  103. }
  104. // isPodStatusByKubeletEqual returns true if the given pod statuses are equal when non-kubelet-owned
  105. // pod conditions are excluded.
  106. // This method normalizes the status before comparing so as to make sure that meaningless
  107. // changes will be ignored.
  108. func isPodStatusByKubeletEqual(oldStatus, status *v1.PodStatus) bool {
  109. oldCopy := oldStatus.DeepCopy()
  110. for _, c := range status.Conditions {
  111. if kubetypes.PodConditionByKubelet(c.Type) {
  112. _, oc := podutil.GetPodCondition(oldCopy, c.Type)
  113. if oc == nil || oc.Status != c.Status || oc.Message != c.Message || oc.Reason != c.Reason {
  114. return false
  115. }
  116. }
  117. }
  118. oldCopy.Conditions = status.Conditions
  119. return apiequality.Semantic.DeepEqual(oldCopy, status)
  120. }
  121. func (m *manager) Start() {
  122. // Don't start the status manager if we don't have a client. This will happen
  123. // on the master, where the kubelet is responsible for bootstrapping the pods
  124. // of the master components.
  125. if m.kubeClient == nil {
  126. klog.Infof("Kubernetes client is nil, not starting status manager.")
  127. return
  128. }
  129. klog.Info("Starting to sync pod status with apiserver")
  130. syncTicker := time.Tick(syncPeriod)
  131. // syncPod and syncBatch share the same go routine to avoid sync races.
  132. go wait.Forever(func() {
  133. select {
  134. case syncRequest := <-m.podStatusChannel:
  135. klog.V(5).Infof("Status Manager: syncing pod: %q, with status: (%d, %v) from podStatusChannel",
  136. syncRequest.podUID, syncRequest.status.version, syncRequest.status.status)
  137. m.syncPod(syncRequest.podUID, syncRequest.status)
  138. case <-syncTicker:
  139. m.syncBatch()
  140. }
  141. }, 0)
  142. }
  143. func (m *manager) GetPodStatus(uid types.UID) (v1.PodStatus, bool) {
  144. m.podStatusesLock.RLock()
  145. defer m.podStatusesLock.RUnlock()
  146. status, ok := m.podStatuses[types.UID(m.podManager.TranslatePodUID(uid))]
  147. return status.status, ok
  148. }
  149. func (m *manager) SetPodStatus(pod *v1.Pod, status v1.PodStatus) {
  150. m.podStatusesLock.Lock()
  151. defer m.podStatusesLock.Unlock()
  152. for _, c := range pod.Status.Conditions {
  153. if !kubetypes.PodConditionByKubelet(c.Type) {
  154. klog.Errorf("Kubelet is trying to update pod condition %q for pod %q. "+
  155. "But it is not owned by kubelet.", string(c.Type), format.Pod(pod))
  156. }
  157. }
  158. // Make sure we're caching a deep copy.
  159. status = *status.DeepCopy()
  160. // Force a status update if deletion timestamp is set. This is necessary
  161. // because if the pod is in the non-running state, the pod worker still
  162. // needs to be able to trigger an update and/or deletion.
  163. m.updateStatusInternal(pod, status, pod.DeletionTimestamp != nil)
  164. }
  165. func (m *manager) SetContainerReadiness(podUID types.UID, containerID kubecontainer.ContainerID, ready bool) {
  166. m.podStatusesLock.Lock()
  167. defer m.podStatusesLock.Unlock()
  168. pod, ok := m.podManager.GetPodByUID(podUID)
  169. if !ok {
  170. klog.V(4).Infof("Pod %q has been deleted, no need to update readiness", string(podUID))
  171. return
  172. }
  173. oldStatus, found := m.podStatuses[pod.UID]
  174. if !found {
  175. klog.Warningf("Container readiness changed before pod has synced: %q - %q",
  176. format.Pod(pod), containerID.String())
  177. return
  178. }
  179. // Find the container to update.
  180. containerStatus, _, ok := findContainerStatus(&oldStatus.status, containerID.String())
  181. if !ok {
  182. klog.Warningf("Container readiness changed for unknown container: %q - %q",
  183. format.Pod(pod), containerID.String())
  184. return
  185. }
  186. if containerStatus.Ready == ready {
  187. klog.V(4).Infof("Container readiness unchanged (%v): %q - %q", ready,
  188. format.Pod(pod), containerID.String())
  189. return
  190. }
  191. // Make sure we're not updating the cached version.
  192. status := *oldStatus.status.DeepCopy()
  193. containerStatus, _, _ = findContainerStatus(&status, containerID.String())
  194. containerStatus.Ready = ready
  195. // updateConditionFunc updates the corresponding type of condition
  196. updateConditionFunc := func(conditionType v1.PodConditionType, condition v1.PodCondition) {
  197. conditionIndex := -1
  198. for i, condition := range status.Conditions {
  199. if condition.Type == conditionType {
  200. conditionIndex = i
  201. break
  202. }
  203. }
  204. if conditionIndex != -1 {
  205. status.Conditions[conditionIndex] = condition
  206. } else {
  207. klog.Warningf("PodStatus missing %s type condition: %+v", conditionType, status)
  208. status.Conditions = append(status.Conditions, condition)
  209. }
  210. }
  211. updateConditionFunc(v1.PodReady, GeneratePodReadyCondition(&pod.Spec, status.Conditions, status.ContainerStatuses, status.Phase))
  212. updateConditionFunc(v1.ContainersReady, GenerateContainersReadyCondition(&pod.Spec, status.ContainerStatuses, status.Phase))
  213. m.updateStatusInternal(pod, status, false)
  214. }
  215. func findContainerStatus(status *v1.PodStatus, containerID string) (containerStatus *v1.ContainerStatus, init bool, ok bool) {
  216. // Find the container to update.
  217. for i, c := range status.ContainerStatuses {
  218. if c.ContainerID == containerID {
  219. return &status.ContainerStatuses[i], false, true
  220. }
  221. }
  222. for i, c := range status.InitContainerStatuses {
  223. if c.ContainerID == containerID {
  224. return &status.InitContainerStatuses[i], true, true
  225. }
  226. }
  227. return nil, false, false
  228. }
  229. func (m *manager) TerminatePod(pod *v1.Pod) {
  230. m.podStatusesLock.Lock()
  231. defer m.podStatusesLock.Unlock()
  232. oldStatus := &pod.Status
  233. if cachedStatus, ok := m.podStatuses[pod.UID]; ok {
  234. oldStatus = &cachedStatus.status
  235. }
  236. status := *oldStatus.DeepCopy()
  237. for i := range status.ContainerStatuses {
  238. status.ContainerStatuses[i].State = v1.ContainerState{
  239. Terminated: &v1.ContainerStateTerminated{},
  240. }
  241. }
  242. for i := range status.InitContainerStatuses {
  243. status.InitContainerStatuses[i].State = v1.ContainerState{
  244. Terminated: &v1.ContainerStateTerminated{},
  245. }
  246. }
  247. m.updateStatusInternal(pod, status, true)
  248. }
  249. // checkContainerStateTransition ensures that no container is trying to transition
  250. // from a terminated to non-terminated state, which is illegal and indicates a
  251. // logical error in the kubelet.
  252. func checkContainerStateTransition(oldStatuses, newStatuses []v1.ContainerStatus, restartPolicy v1.RestartPolicy) error {
  253. // If we should always restart, containers are allowed to leave the terminated state
  254. if restartPolicy == v1.RestartPolicyAlways {
  255. return nil
  256. }
  257. for _, oldStatus := range oldStatuses {
  258. // Skip any container that wasn't terminated
  259. if oldStatus.State.Terminated == nil {
  260. continue
  261. }
  262. // Skip any container that failed but is allowed to restart
  263. if oldStatus.State.Terminated.ExitCode != 0 && restartPolicy == v1.RestartPolicyOnFailure {
  264. continue
  265. }
  266. for _, newStatus := range newStatuses {
  267. if oldStatus.Name == newStatus.Name && newStatus.State.Terminated == nil {
  268. return fmt.Errorf("terminated container %v attempted illegal transition to non-terminated state", newStatus.Name)
  269. }
  270. }
  271. }
  272. return nil
  273. }
  274. // updateStatusInternal updates the internal status cache, and queues an update to the api server if
  275. // necessary. Returns whether an update was triggered.
  276. // This method IS NOT THREAD SAFE and must be called from a locked function.
  277. func (m *manager) updateStatusInternal(pod *v1.Pod, status v1.PodStatus, forceUpdate bool) bool {
  278. var oldStatus v1.PodStatus
  279. cachedStatus, isCached := m.podStatuses[pod.UID]
  280. if isCached {
  281. oldStatus = cachedStatus.status
  282. } else if mirrorPod, ok := m.podManager.GetMirrorPodByPod(pod); ok {
  283. oldStatus = mirrorPod.Status
  284. } else {
  285. oldStatus = pod.Status
  286. }
  287. // Check for illegal state transition in containers
  288. if err := checkContainerStateTransition(oldStatus.ContainerStatuses, status.ContainerStatuses, pod.Spec.RestartPolicy); err != nil {
  289. klog.Errorf("Status update on pod %v/%v aborted: %v", pod.Namespace, pod.Name, err)
  290. return false
  291. }
  292. if err := checkContainerStateTransition(oldStatus.InitContainerStatuses, status.InitContainerStatuses, pod.Spec.RestartPolicy); err != nil {
  293. klog.Errorf("Status update on pod %v/%v aborted: %v", pod.Namespace, pod.Name, err)
  294. return false
  295. }
  296. // Set ContainersReadyCondition.LastTransitionTime.
  297. updateLastTransitionTime(&status, &oldStatus, v1.ContainersReady)
  298. // Set ReadyCondition.LastTransitionTime.
  299. updateLastTransitionTime(&status, &oldStatus, v1.PodReady)
  300. // Set InitializedCondition.LastTransitionTime.
  301. updateLastTransitionTime(&status, &oldStatus, v1.PodInitialized)
  302. // Set PodScheduledCondition.LastTransitionTime.
  303. updateLastTransitionTime(&status, &oldStatus, v1.PodScheduled)
  304. // ensure that the start time does not change across updates.
  305. if oldStatus.StartTime != nil && !oldStatus.StartTime.IsZero() {
  306. status.StartTime = oldStatus.StartTime
  307. } else if status.StartTime.IsZero() {
  308. // if the status has no start time, we need to set an initial time
  309. now := metav1.Now()
  310. status.StartTime = &now
  311. }
  312. normalizeStatus(pod, &status)
  313. // The intent here is to prevent concurrent updates to a pod's status from
  314. // clobbering each other so the phase of a pod progresses monotonically.
  315. if isCached && isPodStatusByKubeletEqual(&cachedStatus.status, &status) && !forceUpdate {
  316. klog.V(3).Infof("Ignoring same status for pod %q, status: %+v", format.Pod(pod), status)
  317. return false // No new status.
  318. }
  319. newStatus := versionedPodStatus{
  320. status: status,
  321. version: cachedStatus.version + 1,
  322. podName: pod.Name,
  323. podNamespace: pod.Namespace,
  324. }
  325. m.podStatuses[pod.UID] = newStatus
  326. select {
  327. case m.podStatusChannel <- podStatusSyncRequest{pod.UID, newStatus}:
  328. klog.V(5).Infof("Status Manager: adding pod: %q, with status: (%d, %v) to podStatusChannel",
  329. pod.UID, newStatus.version, newStatus.status)
  330. return true
  331. default:
  332. // Let the periodic syncBatch handle the update if the channel is full.
  333. // We can't block, since we hold the mutex lock.
  334. klog.V(4).Infof("Skipping the status update for pod %q for now because the channel is full; status: %+v",
  335. format.Pod(pod), status)
  336. return false
  337. }
  338. }
  339. // updateLastTransitionTime updates the LastTransitionTime of a pod condition.
  340. func updateLastTransitionTime(status, oldStatus *v1.PodStatus, conditionType v1.PodConditionType) {
  341. _, condition := podutil.GetPodCondition(status, conditionType)
  342. if condition == nil {
  343. return
  344. }
  345. // Need to set LastTransitionTime.
  346. lastTransitionTime := metav1.Now()
  347. _, oldCondition := podutil.GetPodCondition(oldStatus, conditionType)
  348. if oldCondition != nil && condition.Status == oldCondition.Status {
  349. lastTransitionTime = oldCondition.LastTransitionTime
  350. }
  351. condition.LastTransitionTime = lastTransitionTime
  352. }
  353. // deletePodStatus simply removes the given pod from the status cache.
  354. func (m *manager) deletePodStatus(uid types.UID) {
  355. m.podStatusesLock.Lock()
  356. defer m.podStatusesLock.Unlock()
  357. delete(m.podStatuses, uid)
  358. }
  359. // TODO(filipg): It'd be cleaner if we can do this without signal from user.
  360. func (m *manager) RemoveOrphanedStatuses(podUIDs map[types.UID]bool) {
  361. m.podStatusesLock.Lock()
  362. defer m.podStatusesLock.Unlock()
  363. for key := range m.podStatuses {
  364. if _, ok := podUIDs[key]; !ok {
  365. klog.V(5).Infof("Removing %q from status map.", key)
  366. delete(m.podStatuses, key)
  367. }
  368. }
  369. }
  370. // syncBatch syncs pods statuses with the apiserver.
  371. func (m *manager) syncBatch() {
  372. var updatedStatuses []podStatusSyncRequest
  373. podToMirror, mirrorToPod := m.podManager.GetUIDTranslations()
  374. func() { // Critical section
  375. m.podStatusesLock.RLock()
  376. defer m.podStatusesLock.RUnlock()
  377. // Clean up orphaned versions.
  378. for uid := range m.apiStatusVersions {
  379. _, hasPod := m.podStatuses[types.UID(uid)]
  380. _, hasMirror := mirrorToPod[uid]
  381. if !hasPod && !hasMirror {
  382. delete(m.apiStatusVersions, uid)
  383. }
  384. }
  385. for uid, status := range m.podStatuses {
  386. syncedUID := kubetypes.MirrorPodUID(uid)
  387. if mirrorUID, ok := podToMirror[kubetypes.ResolvedPodUID(uid)]; ok {
  388. if mirrorUID == "" {
  389. klog.V(5).Infof("Static pod %q (%s/%s) does not have a corresponding mirror pod; skipping", uid, status.podName, status.podNamespace)
  390. continue
  391. }
  392. syncedUID = mirrorUID
  393. }
  394. if m.needsUpdate(types.UID(syncedUID), status) {
  395. updatedStatuses = append(updatedStatuses, podStatusSyncRequest{uid, status})
  396. } else if m.needsReconcile(uid, status.status) {
  397. // Delete the apiStatusVersions here to force an update on the pod status
  398. // In most cases the deleted apiStatusVersions here should be filled
  399. // soon after the following syncPod() [If the syncPod() sync an update
  400. // successfully].
  401. delete(m.apiStatusVersions, syncedUID)
  402. updatedStatuses = append(updatedStatuses, podStatusSyncRequest{uid, status})
  403. }
  404. }
  405. }()
  406. for _, update := range updatedStatuses {
  407. klog.V(5).Infof("Status Manager: syncPod in syncbatch. pod UID: %q", update.podUID)
  408. m.syncPod(update.podUID, update.status)
  409. }
  410. }
  411. // syncPod syncs the given status with the API server. The caller must not hold the lock.
  412. func (m *manager) syncPod(uid types.UID, status versionedPodStatus) {
  413. if !m.needsUpdate(uid, status) {
  414. klog.V(1).Infof("Status for pod %q is up-to-date; skipping", uid)
  415. return
  416. }
  417. // TODO: make me easier to express from client code
  418. pod, err := m.kubeClient.CoreV1().Pods(status.podNamespace).Get(status.podName, metav1.GetOptions{})
  419. if errors.IsNotFound(err) {
  420. klog.V(3).Infof("Pod %q (%s) does not exist on the server", status.podName, uid)
  421. // If the Pod is deleted the status will be cleared in
  422. // RemoveOrphanedStatuses, so we just ignore the update here.
  423. return
  424. }
  425. if err != nil {
  426. klog.Warningf("Failed to get status for pod %q: %v", format.PodDesc(status.podName, status.podNamespace, uid), err)
  427. return
  428. }
  429. translatedUID := m.podManager.TranslatePodUID(pod.UID)
  430. // Type convert original uid just for the purpose of comparison.
  431. if len(translatedUID) > 0 && translatedUID != kubetypes.ResolvedPodUID(uid) {
  432. klog.V(2).Infof("Pod %q was deleted and then recreated, skipping status update; old UID %q, new UID %q", format.Pod(pod), uid, translatedUID)
  433. m.deletePodStatus(uid)
  434. return
  435. }
  436. oldStatus := pod.Status.DeepCopy()
  437. newPod, patchBytes, err := statusutil.PatchPodStatus(m.kubeClient, pod.Namespace, pod.Name, *oldStatus, mergePodStatus(*oldStatus, status.status))
  438. klog.V(3).Infof("Patch status for pod %q with %q", format.Pod(pod), patchBytes)
  439. if err != nil {
  440. klog.Warningf("Failed to update status for pod %q: %v", format.Pod(pod), err)
  441. return
  442. }
  443. pod = newPod
  444. klog.V(3).Infof("Status for pod %q updated successfully: (%d, %+v)", format.Pod(pod), status.version, status.status)
  445. m.apiStatusVersions[kubetypes.MirrorPodUID(pod.UID)] = status.version
  446. // We don't handle graceful deletion of mirror pods.
  447. if m.canBeDeleted(pod, status.status) {
  448. deleteOptions := metav1.NewDeleteOptions(0)
  449. // Use the pod UID as the precondition for deletion to prevent deleting a newly created pod with the same name and namespace.
  450. deleteOptions.Preconditions = metav1.NewUIDPreconditions(string(pod.UID))
  451. err = m.kubeClient.CoreV1().Pods(pod.Namespace).Delete(pod.Name, deleteOptions)
  452. if err != nil {
  453. klog.Warningf("Failed to delete status for pod %q: %v", format.Pod(pod), err)
  454. return
  455. }
  456. klog.V(3).Infof("Pod %q fully terminated and removed from etcd", format.Pod(pod))
  457. m.deletePodStatus(uid)
  458. }
  459. }
  460. // needsUpdate returns whether the status is stale for the given pod UID.
  461. // This method is not thread safe, and must only be accessed by the sync thread.
  462. func (m *manager) needsUpdate(uid types.UID, status versionedPodStatus) bool {
  463. latest, ok := m.apiStatusVersions[kubetypes.MirrorPodUID(uid)]
  464. if !ok || latest < status.version {
  465. return true
  466. }
  467. pod, ok := m.podManager.GetPodByUID(uid)
  468. if !ok {
  469. return false
  470. }
  471. return m.canBeDeleted(pod, status.status)
  472. }
  473. func (m *manager) canBeDeleted(pod *v1.Pod, status v1.PodStatus) bool {
  474. if pod.DeletionTimestamp == nil || kubepod.IsMirrorPod(pod) {
  475. return false
  476. }
  477. return m.podDeletionSafety.PodResourcesAreReclaimed(pod, status)
  478. }
  479. // needsReconcile compares the given status with the status in the pod manager (which
  480. // in fact comes from apiserver), returns whether the status needs to be reconciled with
  481. // the apiserver. Now when pod status is inconsistent between apiserver and kubelet,
  482. // kubelet should forcibly send an update to reconcile the inconsistence, because kubelet
  483. // should be the source of truth of pod status.
  484. // NOTE(random-liu): It's simpler to pass in mirror pod uid and get mirror pod by uid, but
  485. // now the pod manager only supports getting mirror pod by static pod, so we have to pass
  486. // static pod uid here.
  487. // TODO(random-liu): Simplify the logic when mirror pod manager is added.
  488. func (m *manager) needsReconcile(uid types.UID, status v1.PodStatus) bool {
  489. // The pod could be a static pod, so we should translate first.
  490. pod, ok := m.podManager.GetPodByUID(uid)
  491. if !ok {
  492. klog.V(4).Infof("Pod %q has been deleted, no need to reconcile", string(uid))
  493. return false
  494. }
  495. // If the pod is a static pod, we should check its mirror pod, because only status in mirror pod is meaningful to us.
  496. if kubepod.IsStaticPod(pod) {
  497. mirrorPod, ok := m.podManager.GetMirrorPodByPod(pod)
  498. if !ok {
  499. klog.V(4).Infof("Static pod %q has no corresponding mirror pod, no need to reconcile", format.Pod(pod))
  500. return false
  501. }
  502. pod = mirrorPod
  503. }
  504. podStatus := pod.Status.DeepCopy()
  505. normalizeStatus(pod, podStatus)
  506. if isPodStatusByKubeletEqual(podStatus, &status) {
  507. // If the status from the source is the same with the cached status,
  508. // reconcile is not needed. Just return.
  509. return false
  510. }
  511. klog.V(3).Infof("Pod status is inconsistent with cached status for pod %q, a reconciliation should be triggered:\n %+v", format.Pod(pod),
  512. diff.ObjectDiff(podStatus, status))
  513. return true
  514. }
  515. // We add this function, because apiserver only supports *RFC3339* now, which means that the timestamp returned by
  516. // apiserver has no nanosecond information. However, the timestamp returned by metav1.Now() contains nanosecond,
  517. // so when we do comparison between status from apiserver and cached status, isPodStatusByKubeletEqual() will always return false.
  518. // There is related issue #15262 and PR #15263 about this.
  519. // In fact, the best way to solve this is to do it on api side. However, for now, we normalize the status locally in
  520. // kubelet temporarily.
  521. // TODO(random-liu): Remove timestamp related logic after apiserver supports nanosecond or makes it consistent.
  522. func normalizeStatus(pod *v1.Pod, status *v1.PodStatus) *v1.PodStatus {
  523. bytesPerStatus := kubecontainer.MaxPodTerminationMessageLogLength
  524. if containers := len(pod.Spec.Containers) + len(pod.Spec.InitContainers); containers > 0 {
  525. bytesPerStatus = bytesPerStatus / containers
  526. }
  527. normalizeTimeStamp := func(t *metav1.Time) {
  528. *t = t.Rfc3339Copy()
  529. }
  530. normalizeContainerState := func(c *v1.ContainerState) {
  531. if c.Running != nil {
  532. normalizeTimeStamp(&c.Running.StartedAt)
  533. }
  534. if c.Terminated != nil {
  535. normalizeTimeStamp(&c.Terminated.StartedAt)
  536. normalizeTimeStamp(&c.Terminated.FinishedAt)
  537. if len(c.Terminated.Message) > bytesPerStatus {
  538. c.Terminated.Message = c.Terminated.Message[:bytesPerStatus]
  539. }
  540. }
  541. }
  542. if status.StartTime != nil {
  543. normalizeTimeStamp(status.StartTime)
  544. }
  545. for i := range status.Conditions {
  546. condition := &status.Conditions[i]
  547. normalizeTimeStamp(&condition.LastProbeTime)
  548. normalizeTimeStamp(&condition.LastTransitionTime)
  549. }
  550. // update container statuses
  551. for i := range status.ContainerStatuses {
  552. cstatus := &status.ContainerStatuses[i]
  553. normalizeContainerState(&cstatus.State)
  554. normalizeContainerState(&cstatus.LastTerminationState)
  555. }
  556. // Sort the container statuses, so that the order won't affect the result of comparison
  557. sort.Sort(kubetypes.SortedContainerStatuses(status.ContainerStatuses))
  558. // update init container statuses
  559. for i := range status.InitContainerStatuses {
  560. cstatus := &status.InitContainerStatuses[i]
  561. normalizeContainerState(&cstatus.State)
  562. normalizeContainerState(&cstatus.LastTerminationState)
  563. }
  564. // Sort the container statuses, so that the order won't affect the result of comparison
  565. kubetypes.SortInitContainerStatuses(pod, status.InitContainerStatuses)
  566. return status
  567. }
  568. // mergePodStatus merges oldPodStatus and newPodStatus where pod conditions
  569. // not owned by kubelet is preserved from oldPodStatus
  570. func mergePodStatus(oldPodStatus, newPodStatus v1.PodStatus) v1.PodStatus {
  571. podConditions := []v1.PodCondition{}
  572. for _, c := range oldPodStatus.Conditions {
  573. if !kubetypes.PodConditionByKubelet(c.Type) {
  574. podConditions = append(podConditions, c)
  575. }
  576. }
  577. for _, c := range newPodStatus.Conditions {
  578. if kubetypes.PodConditionByKubelet(c.Type) {
  579. podConditions = append(podConditions, c)
  580. }
  581. }
  582. newPodStatus.Conditions = podConditions
  583. return newPodStatus
  584. }
  585. // NeedToReconcilePodReadiness returns if the pod "Ready" condition need to be reconcile
  586. func NeedToReconcilePodReadiness(pod *v1.Pod) bool {
  587. if len(pod.Spec.ReadinessGates) == 0 {
  588. return false
  589. }
  590. podReadyCondition := GeneratePodReadyCondition(&pod.Spec, pod.Status.Conditions, pod.Status.ContainerStatuses, pod.Status.Phase)
  591. i, curCondition := podutil.GetPodConditionFromList(pod.Status.Conditions, v1.PodReady)
  592. // Only reconcile if "Ready" condition is present and Status or Message is not expected
  593. if i >= 0 && (curCondition.Status != podReadyCondition.Status || curCondition.Message != podReadyCondition.Message) {
  594. return true
  595. }
  596. return false
  597. }