status_manager_test.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. "math/rand"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "testing"
  21. "time"
  22. "github.com/stretchr/testify/assert"
  23. "k8s.io/api/core/v1"
  24. "k8s.io/apimachinery/pkg/api/errors"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/runtime/schema"
  28. clientset "k8s.io/client-go/kubernetes"
  29. "k8s.io/client-go/kubernetes/fake"
  30. core "k8s.io/client-go/testing"
  31. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  32. api "k8s.io/kubernetes/pkg/apis/core"
  33. kubeconfigmap "k8s.io/kubernetes/pkg/kubelet/configmap"
  34. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  35. kubepod "k8s.io/kubernetes/pkg/kubelet/pod"
  36. podtest "k8s.io/kubernetes/pkg/kubelet/pod/testing"
  37. kubesecret "k8s.io/kubernetes/pkg/kubelet/secret"
  38. statustest "k8s.io/kubernetes/pkg/kubelet/status/testing"
  39. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  40. )
  41. // Generate new instance of test pod with the same initial value.
  42. func getTestPod() *v1.Pod {
  43. return &v1.Pod{
  44. TypeMeta: metav1.TypeMeta{
  45. Kind: "Pod",
  46. APIVersion: "v1",
  47. },
  48. ObjectMeta: metav1.ObjectMeta{
  49. UID: "12345678",
  50. Name: "foo",
  51. Namespace: "new",
  52. },
  53. }
  54. }
  55. // After adding reconciliation, if status in pod manager is different from the cached status, a reconciliation
  56. // will be triggered, which will mess up all the old unit test.
  57. // To simplify the implementation of unit test, we add testSyncBatch() here, it will make sure the statuses in
  58. // pod manager the same with cached ones before syncBatch() so as to avoid reconciling.
  59. func (m *manager) testSyncBatch() {
  60. for uid, status := range m.podStatuses {
  61. pod, ok := m.podManager.GetPodByUID(uid)
  62. if ok {
  63. pod.Status = status.status
  64. }
  65. pod, ok = m.podManager.GetMirrorPodByPod(pod)
  66. if ok {
  67. pod.Status = status.status
  68. }
  69. }
  70. m.syncBatch()
  71. }
  72. func newTestManager(kubeClient clientset.Interface) *manager {
  73. podManager := kubepod.NewBasicPodManager(podtest.NewFakeMirrorClient(), kubesecret.NewFakeManager(), kubeconfigmap.NewFakeManager(), podtest.NewMockCheckpointManager())
  74. podManager.AddPod(getTestPod())
  75. return NewManager(kubeClient, podManager, &statustest.FakePodDeletionSafetyProvider{}).(*manager)
  76. }
  77. func generateRandomMessage() string {
  78. return strconv.Itoa(rand.Int())
  79. }
  80. func getRandomPodStatus() v1.PodStatus {
  81. return v1.PodStatus{
  82. Message: generateRandomMessage(),
  83. }
  84. }
  85. func verifyActions(t *testing.T, manager *manager, expectedActions []core.Action) {
  86. manager.consumeUpdates()
  87. actions := manager.kubeClient.(*fake.Clientset).Actions()
  88. defer manager.kubeClient.(*fake.Clientset).ClearActions()
  89. if len(actions) != len(expectedActions) {
  90. t.Fatalf("unexpected actions, got: %+v expected: %+v", actions, expectedActions)
  91. return
  92. }
  93. for i := 0; i < len(actions); i++ {
  94. e := expectedActions[i]
  95. a := actions[i]
  96. if !a.Matches(e.GetVerb(), e.GetResource().Resource) || a.GetSubresource() != e.GetSubresource() {
  97. t.Errorf("unexpected actions, got: %+v expected: %+v", actions, expectedActions)
  98. }
  99. }
  100. }
  101. func verifyUpdates(t *testing.T, manager *manager, expectedUpdates int) {
  102. // Consume all updates in the channel.
  103. numUpdates := manager.consumeUpdates()
  104. if numUpdates != expectedUpdates {
  105. t.Errorf("unexpected number of updates %d, expected %d", numUpdates, expectedUpdates)
  106. }
  107. }
  108. func (m *manager) consumeUpdates() int {
  109. updates := 0
  110. for {
  111. select {
  112. case syncRequest := <-m.podStatusChannel:
  113. m.syncPod(syncRequest.podUID, syncRequest.status)
  114. updates++
  115. default:
  116. return updates
  117. }
  118. }
  119. }
  120. func TestNewStatus(t *testing.T) {
  121. syncer := newTestManager(&fake.Clientset{})
  122. testPod := getTestPod()
  123. syncer.SetPodStatus(testPod, getRandomPodStatus())
  124. verifyUpdates(t, syncer, 1)
  125. status := expectPodStatus(t, syncer, testPod)
  126. if status.StartTime.IsZero() {
  127. t.Errorf("SetPodStatus did not set a proper start time value")
  128. }
  129. }
  130. func TestNewStatusPreservesPodStartTime(t *testing.T) {
  131. syncer := newTestManager(&fake.Clientset{})
  132. pod := &v1.Pod{
  133. ObjectMeta: metav1.ObjectMeta{
  134. UID: "12345678",
  135. Name: "foo",
  136. Namespace: "new",
  137. },
  138. Status: v1.PodStatus{},
  139. }
  140. now := metav1.Now()
  141. startTime := metav1.NewTime(now.Time.Add(-1 * time.Minute))
  142. pod.Status.StartTime = &startTime
  143. syncer.SetPodStatus(pod, getRandomPodStatus())
  144. status := expectPodStatus(t, syncer, pod)
  145. if !status.StartTime.Time.Equal(startTime.Time) {
  146. t.Errorf("Unexpected start time, expected %v, actual %v", startTime, status.StartTime)
  147. }
  148. }
  149. func getReadyPodStatus() v1.PodStatus {
  150. return v1.PodStatus{
  151. Conditions: []v1.PodCondition{
  152. {
  153. Type: v1.PodReady,
  154. Status: v1.ConditionTrue,
  155. },
  156. },
  157. }
  158. }
  159. func TestNewStatusSetsReadyTransitionTime(t *testing.T) {
  160. syncer := newTestManager(&fake.Clientset{})
  161. podStatus := getReadyPodStatus()
  162. pod := &v1.Pod{
  163. ObjectMeta: metav1.ObjectMeta{
  164. UID: "12345678",
  165. Name: "foo",
  166. Namespace: "new",
  167. },
  168. Status: v1.PodStatus{},
  169. }
  170. syncer.SetPodStatus(pod, podStatus)
  171. verifyUpdates(t, syncer, 1)
  172. status := expectPodStatus(t, syncer, pod)
  173. readyCondition := podutil.GetPodReadyCondition(status)
  174. if readyCondition.LastTransitionTime.IsZero() {
  175. t.Errorf("Unexpected: last transition time not set")
  176. }
  177. }
  178. func TestChangedStatus(t *testing.T) {
  179. syncer := newTestManager(&fake.Clientset{})
  180. testPod := getTestPod()
  181. syncer.SetPodStatus(testPod, getRandomPodStatus())
  182. syncer.SetPodStatus(testPod, getRandomPodStatus())
  183. verifyUpdates(t, syncer, 2)
  184. }
  185. func TestChangedStatusKeepsStartTime(t *testing.T) {
  186. syncer := newTestManager(&fake.Clientset{})
  187. testPod := getTestPod()
  188. now := metav1.Now()
  189. firstStatus := getRandomPodStatus()
  190. firstStatus.StartTime = &now
  191. syncer.SetPodStatus(testPod, firstStatus)
  192. syncer.SetPodStatus(testPod, getRandomPodStatus())
  193. verifyUpdates(t, syncer, 2)
  194. finalStatus := expectPodStatus(t, syncer, testPod)
  195. if finalStatus.StartTime.IsZero() {
  196. t.Errorf("StartTime should not be zero")
  197. }
  198. expected := now.Rfc3339Copy()
  199. if !finalStatus.StartTime.Equal(&expected) {
  200. t.Errorf("Expected %v, but got %v", expected, finalStatus.StartTime)
  201. }
  202. }
  203. func TestChangedStatusUpdatesLastTransitionTime(t *testing.T) {
  204. syncer := newTestManager(&fake.Clientset{})
  205. podStatus := getReadyPodStatus()
  206. pod := &v1.Pod{
  207. ObjectMeta: metav1.ObjectMeta{
  208. UID: "12345678",
  209. Name: "foo",
  210. Namespace: "new",
  211. },
  212. Status: v1.PodStatus{},
  213. }
  214. syncer.SetPodStatus(pod, podStatus)
  215. verifyUpdates(t, syncer, 1)
  216. oldStatus := expectPodStatus(t, syncer, pod)
  217. anotherStatus := getReadyPodStatus()
  218. anotherStatus.Conditions[0].Status = v1.ConditionFalse
  219. syncer.SetPodStatus(pod, anotherStatus)
  220. verifyUpdates(t, syncer, 1)
  221. newStatus := expectPodStatus(t, syncer, pod)
  222. oldReadyCondition := podutil.GetPodReadyCondition(oldStatus)
  223. newReadyCondition := podutil.GetPodReadyCondition(newStatus)
  224. if newReadyCondition.LastTransitionTime.IsZero() {
  225. t.Errorf("Unexpected: last transition time not set")
  226. }
  227. if newReadyCondition.LastTransitionTime.Before(&oldReadyCondition.LastTransitionTime) {
  228. t.Errorf("Unexpected: new transition time %s, is before old transition time %s", newReadyCondition.LastTransitionTime, oldReadyCondition.LastTransitionTime)
  229. }
  230. }
  231. func TestUnchangedStatus(t *testing.T) {
  232. syncer := newTestManager(&fake.Clientset{})
  233. testPod := getTestPod()
  234. podStatus := getRandomPodStatus()
  235. syncer.SetPodStatus(testPod, podStatus)
  236. syncer.SetPodStatus(testPod, podStatus)
  237. verifyUpdates(t, syncer, 1)
  238. }
  239. func TestUnchangedStatusPreservesLastTransitionTime(t *testing.T) {
  240. syncer := newTestManager(&fake.Clientset{})
  241. podStatus := getReadyPodStatus()
  242. pod := &v1.Pod{
  243. ObjectMeta: metav1.ObjectMeta{
  244. UID: "12345678",
  245. Name: "foo",
  246. Namespace: "new",
  247. },
  248. Status: v1.PodStatus{},
  249. }
  250. syncer.SetPodStatus(pod, podStatus)
  251. verifyUpdates(t, syncer, 1)
  252. oldStatus := expectPodStatus(t, syncer, pod)
  253. anotherStatus := getReadyPodStatus()
  254. syncer.SetPodStatus(pod, anotherStatus)
  255. // No update.
  256. verifyUpdates(t, syncer, 0)
  257. newStatus := expectPodStatus(t, syncer, pod)
  258. oldReadyCondition := podutil.GetPodReadyCondition(oldStatus)
  259. newReadyCondition := podutil.GetPodReadyCondition(newStatus)
  260. if newReadyCondition.LastTransitionTime.IsZero() {
  261. t.Errorf("Unexpected: last transition time not set")
  262. }
  263. if !oldReadyCondition.LastTransitionTime.Equal(&newReadyCondition.LastTransitionTime) {
  264. t.Errorf("Unexpected: new transition time %s, is not equal to old transition time %s", newReadyCondition.LastTransitionTime, oldReadyCondition.LastTransitionTime)
  265. }
  266. }
  267. func TestSyncPodIgnoresNotFound(t *testing.T) {
  268. client := fake.Clientset{}
  269. syncer := newTestManager(&client)
  270. client.AddReactor("get", "pods", func(action core.Action) (bool, runtime.Object, error) {
  271. return true, nil, errors.NewNotFound(api.Resource("pods"), "test-pod")
  272. })
  273. syncer.SetPodStatus(getTestPod(), getRandomPodStatus())
  274. verifyActions(t, syncer, []core.Action{getAction()})
  275. }
  276. func TestSyncPod(t *testing.T) {
  277. syncer := newTestManager(&fake.Clientset{})
  278. testPod := getTestPod()
  279. syncer.kubeClient = fake.NewSimpleClientset(testPod)
  280. syncer.SetPodStatus(testPod, getRandomPodStatus())
  281. verifyActions(t, syncer, []core.Action{getAction(), patchAction()})
  282. }
  283. func TestSyncPodChecksMismatchedUID(t *testing.T) {
  284. syncer := newTestManager(&fake.Clientset{})
  285. pod := getTestPod()
  286. pod.UID = "first"
  287. syncer.podManager.AddPod(pod)
  288. differentPod := getTestPod()
  289. differentPod.UID = "second"
  290. syncer.podManager.AddPod(differentPod)
  291. syncer.kubeClient = fake.NewSimpleClientset(pod)
  292. syncer.SetPodStatus(differentPod, getRandomPodStatus())
  293. verifyActions(t, syncer, []core.Action{getAction()})
  294. }
  295. func TestSyncPodNoDeadlock(t *testing.T) {
  296. client := &fake.Clientset{}
  297. m := newTestManager(client)
  298. pod := getTestPod()
  299. // Setup fake client.
  300. var ret *v1.Pod
  301. var err error
  302. client.AddReactor("*", "pods", func(action core.Action) (bool, runtime.Object, error) {
  303. switch action := action.(type) {
  304. case core.GetAction:
  305. assert.Equal(t, pod.Name, action.GetName(), "Unexpected GetAction: %+v", action)
  306. case core.UpdateAction:
  307. assert.Equal(t, pod.Name, action.GetObject().(*v1.Pod).Name, "Unexpected UpdateAction: %+v", action)
  308. default:
  309. assert.Fail(t, "Unexpected Action: %+v", action)
  310. }
  311. return true, ret, err
  312. })
  313. pod.Status.ContainerStatuses = []v1.ContainerStatus{{State: v1.ContainerState{Running: &v1.ContainerStateRunning{}}}}
  314. t.Logf("Pod not found.")
  315. ret = nil
  316. err = errors.NewNotFound(api.Resource("pods"), pod.Name)
  317. m.SetPodStatus(pod, getRandomPodStatus())
  318. verifyActions(t, m, []core.Action{getAction()})
  319. t.Logf("Pod was recreated.")
  320. ret = getTestPod()
  321. ret.UID = "other_pod"
  322. err = nil
  323. m.SetPodStatus(pod, getRandomPodStatus())
  324. verifyActions(t, m, []core.Action{getAction()})
  325. t.Logf("Pod not deleted (success case).")
  326. ret = getTestPod()
  327. m.SetPodStatus(pod, getRandomPodStatus())
  328. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  329. t.Logf("Pod is terminated, but still running.")
  330. pod.DeletionTimestamp = &metav1.Time{Time: time.Now()}
  331. m.SetPodStatus(pod, getRandomPodStatus())
  332. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  333. t.Logf("Pod is terminated successfully.")
  334. pod.Status.ContainerStatuses[0].State.Running = nil
  335. pod.Status.ContainerStatuses[0].State.Terminated = &v1.ContainerStateTerminated{}
  336. m.SetPodStatus(pod, getRandomPodStatus())
  337. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  338. t.Logf("Error case.")
  339. ret = nil
  340. err = fmt.Errorf("intentional test error")
  341. m.SetPodStatus(pod, getRandomPodStatus())
  342. verifyActions(t, m, []core.Action{getAction()})
  343. }
  344. func TestStaleUpdates(t *testing.T) {
  345. pod := getTestPod()
  346. client := fake.NewSimpleClientset(pod)
  347. m := newTestManager(client)
  348. status := v1.PodStatus{Message: "initial status"}
  349. m.SetPodStatus(pod, status)
  350. status.Message = "first version bump"
  351. m.SetPodStatus(pod, status)
  352. status.Message = "second version bump"
  353. m.SetPodStatus(pod, status)
  354. t.Logf("sync batch before syncPods pushes latest status, so we should see three statuses in the channel, but only one update")
  355. m.syncBatch()
  356. verifyUpdates(t, m, 3)
  357. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  358. t.Logf("Nothing left in the channel to sync")
  359. verifyActions(t, m, []core.Action{})
  360. t.Log("Unchanged status should not send an update.")
  361. m.SetPodStatus(pod, status)
  362. verifyUpdates(t, m, 0)
  363. t.Log("... unless it's stale.")
  364. mirrorPodUID := kubetypes.MirrorPodUID(pod.UID)
  365. m.apiStatusVersions[mirrorPodUID] = m.apiStatusVersions[mirrorPodUID] - 1
  366. m.SetPodStatus(pod, status)
  367. m.syncBatch()
  368. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  369. t.Logf("Nothing stuck in the pipe.")
  370. verifyUpdates(t, m, 0)
  371. }
  372. // shuffle returns a new shuffled list of container statuses.
  373. func shuffle(statuses []v1.ContainerStatus) []v1.ContainerStatus {
  374. numStatuses := len(statuses)
  375. randIndexes := rand.Perm(numStatuses)
  376. shuffled := make([]v1.ContainerStatus, numStatuses)
  377. for i := 0; i < numStatuses; i++ {
  378. shuffled[i] = statuses[randIndexes[i]]
  379. }
  380. return shuffled
  381. }
  382. func TestStatusEquality(t *testing.T) {
  383. pod := v1.Pod{
  384. Spec: v1.PodSpec{},
  385. }
  386. containerStatus := []v1.ContainerStatus{}
  387. for i := 0; i < 10; i++ {
  388. s := v1.ContainerStatus{
  389. Name: fmt.Sprintf("container%d", i),
  390. }
  391. containerStatus = append(containerStatus, s)
  392. }
  393. podStatus := v1.PodStatus{
  394. ContainerStatuses: containerStatus,
  395. }
  396. for i := 0; i < 10; i++ {
  397. oldPodStatus := v1.PodStatus{
  398. ContainerStatuses: shuffle(podStatus.ContainerStatuses),
  399. }
  400. normalizeStatus(&pod, &oldPodStatus)
  401. normalizeStatus(&pod, &podStatus)
  402. if !isPodStatusByKubeletEqual(&oldPodStatus, &podStatus) {
  403. t.Fatalf("Order of container statuses should not affect normalized equality.")
  404. }
  405. }
  406. oldPodStatus := podStatus
  407. podStatus.Conditions = append(podStatus.Conditions, v1.PodCondition{
  408. Type: v1.PodConditionType("www.example.com/feature"),
  409. Status: v1.ConditionTrue,
  410. })
  411. oldPodStatus.Conditions = append(podStatus.Conditions, v1.PodCondition{
  412. Type: v1.PodConditionType("www.example.com/feature"),
  413. Status: v1.ConditionFalse,
  414. })
  415. normalizeStatus(&pod, &oldPodStatus)
  416. normalizeStatus(&pod, &podStatus)
  417. if !isPodStatusByKubeletEqual(&oldPodStatus, &podStatus) {
  418. t.Fatalf("Differences in pod condition not owned by kubelet should not affect normalized equality.")
  419. }
  420. }
  421. func TestStatusNormalizationEnforcesMaxBytes(t *testing.T) {
  422. pod := v1.Pod{
  423. Spec: v1.PodSpec{},
  424. }
  425. containerStatus := []v1.ContainerStatus{}
  426. for i := 0; i < 48; i++ {
  427. s := v1.ContainerStatus{
  428. Name: fmt.Sprintf("container%d", i),
  429. LastTerminationState: v1.ContainerState{
  430. Terminated: &v1.ContainerStateTerminated{
  431. Message: strings.Repeat("abcdefgh", int(24+i%3)),
  432. },
  433. },
  434. }
  435. containerStatus = append(containerStatus, s)
  436. }
  437. podStatus := v1.PodStatus{
  438. InitContainerStatuses: containerStatus[:24],
  439. ContainerStatuses: containerStatus[24:],
  440. }
  441. result := normalizeStatus(&pod, &podStatus)
  442. count := 0
  443. for _, s := range result.InitContainerStatuses {
  444. l := len(s.LastTerminationState.Terminated.Message)
  445. if l < 192 || l > 256 {
  446. t.Errorf("container message had length %d", l)
  447. }
  448. count += l
  449. }
  450. if count > kubecontainer.MaxPodTerminationMessageLogLength {
  451. t.Errorf("message length not truncated")
  452. }
  453. }
  454. func TestStaticPod(t *testing.T) {
  455. staticPod := getTestPod()
  456. staticPod.Annotations = map[string]string{kubetypes.ConfigSourceAnnotationKey: "file"}
  457. mirrorPod := getTestPod()
  458. mirrorPod.UID = "mirror-12345678"
  459. mirrorPod.Annotations = map[string]string{
  460. kubetypes.ConfigSourceAnnotationKey: "api",
  461. kubetypes.ConfigMirrorAnnotationKey: "mirror",
  462. }
  463. client := fake.NewSimpleClientset(mirrorPod)
  464. m := newTestManager(client)
  465. t.Logf("Create the static pod")
  466. m.podManager.AddPod(staticPod)
  467. assert.True(t, kubetypes.IsStaticPod(staticPod), "SetUp error: staticPod")
  468. status := getRandomPodStatus()
  469. now := metav1.Now()
  470. status.StartTime = &now
  471. m.SetPodStatus(staticPod, status)
  472. t.Logf("Should be able to get the static pod status from status manager")
  473. retrievedStatus := expectPodStatus(t, m, staticPod)
  474. normalizeStatus(staticPod, &status)
  475. assert.True(t, isPodStatusByKubeletEqual(&status, &retrievedStatus), "Expected: %+v, Got: %+v", status, retrievedStatus)
  476. t.Logf("Should not sync pod in syncBatch because there is no corresponding mirror pod for the static pod.")
  477. m.syncBatch()
  478. assert.Equal(t, len(m.kubeClient.(*fake.Clientset).Actions()), 0, "Expected no updates after syncBatch, got %+v", m.kubeClient.(*fake.Clientset).Actions())
  479. t.Logf("Create the mirror pod")
  480. m.podManager.AddPod(mirrorPod)
  481. assert.True(t, kubetypes.IsMirrorPod(mirrorPod), "SetUp error: mirrorPod")
  482. assert.Equal(t, m.podManager.TranslatePodUID(mirrorPod.UID), kubetypes.ResolvedPodUID(staticPod.UID))
  483. t.Logf("Should be able to get the mirror pod status from status manager")
  484. retrievedStatus, _ = m.GetPodStatus(mirrorPod.UID)
  485. assert.True(t, isPodStatusByKubeletEqual(&status, &retrievedStatus), "Expected: %+v, Got: %+v", status, retrievedStatus)
  486. t.Logf("Should sync pod because the corresponding mirror pod is created")
  487. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  488. t.Logf("syncBatch should not sync any pods because nothing is changed.")
  489. m.testSyncBatch()
  490. verifyActions(t, m, []core.Action{})
  491. t.Logf("Change mirror pod identity.")
  492. m.podManager.DeletePod(mirrorPod)
  493. mirrorPod.UID = "new-mirror-pod"
  494. mirrorPod.Status = v1.PodStatus{}
  495. m.podManager.AddPod(mirrorPod)
  496. t.Logf("Should not update to mirror pod, because UID has changed.")
  497. m.syncBatch()
  498. verifyActions(t, m, []core.Action{getAction()})
  499. }
  500. func TestTerminatePod(t *testing.T) {
  501. syncer := newTestManager(&fake.Clientset{})
  502. testPod := getTestPod()
  503. t.Logf("update the pod's status to Failed. TerminatePod should preserve this status update.")
  504. firstStatus := getRandomPodStatus()
  505. firstStatus.Phase = v1.PodFailed
  506. syncer.SetPodStatus(testPod, firstStatus)
  507. t.Logf("set the testPod to a pod with Phase running, to simulate a stale pod")
  508. testPod.Status = getRandomPodStatus()
  509. testPod.Status.Phase = v1.PodRunning
  510. syncer.TerminatePod(testPod)
  511. t.Logf("we expect the container statuses to have changed to terminated")
  512. newStatus := expectPodStatus(t, syncer, testPod)
  513. for i := range newStatus.ContainerStatuses {
  514. assert.False(t, newStatus.ContainerStatuses[i].State.Terminated == nil, "expected containers to be terminated")
  515. }
  516. for i := range newStatus.InitContainerStatuses {
  517. assert.False(t, newStatus.InitContainerStatuses[i].State.Terminated == nil, "expected init containers to be terminated")
  518. }
  519. t.Logf("we expect the previous status update to be preserved.")
  520. assert.Equal(t, newStatus.Phase, firstStatus.Phase)
  521. assert.Equal(t, newStatus.Message, firstStatus.Message)
  522. }
  523. func TestSetContainerReadiness(t *testing.T) {
  524. cID1 := kubecontainer.ContainerID{Type: "test", ID: "1"}
  525. cID2 := kubecontainer.ContainerID{Type: "test", ID: "2"}
  526. containerStatuses := []v1.ContainerStatus{
  527. {
  528. Name: "c1",
  529. ContainerID: cID1.String(),
  530. Ready: false,
  531. }, {
  532. Name: "c2",
  533. ContainerID: cID2.String(),
  534. Ready: false,
  535. },
  536. }
  537. status := v1.PodStatus{
  538. ContainerStatuses: containerStatuses,
  539. Conditions: []v1.PodCondition{{
  540. Type: v1.PodReady,
  541. Status: v1.ConditionFalse,
  542. }},
  543. }
  544. pod := getTestPod()
  545. pod.Spec.Containers = []v1.Container{{Name: "c1"}, {Name: "c2"}}
  546. // Verify expected readiness of containers & pod.
  547. verifyReadiness := func(step string, status *v1.PodStatus, c1Ready, c2Ready, podReady bool) {
  548. for _, c := range status.ContainerStatuses {
  549. switch c.ContainerID {
  550. case cID1.String():
  551. if c.Ready != c1Ready {
  552. t.Errorf("[%s] Expected readiness of c1 to be %v but was %v", step, c1Ready, c.Ready)
  553. }
  554. case cID2.String():
  555. if c.Ready != c2Ready {
  556. t.Errorf("[%s] Expected readiness of c2 to be %v but was %v", step, c2Ready, c.Ready)
  557. }
  558. default:
  559. t.Fatalf("[%s] Unexpected container: %+v", step, c)
  560. }
  561. }
  562. if status.Conditions[0].Type != v1.PodReady {
  563. t.Fatalf("[%s] Unexpected condition: %+v", step, status.Conditions[0])
  564. } else if ready := (status.Conditions[0].Status == v1.ConditionTrue); ready != podReady {
  565. t.Errorf("[%s] Expected readiness of pod to be %v but was %v", step, podReady, ready)
  566. }
  567. }
  568. m := newTestManager(&fake.Clientset{})
  569. // Add test pod because the container spec has been changed.
  570. m.podManager.AddPod(pod)
  571. t.Log("Setting readiness before status should fail.")
  572. m.SetContainerReadiness(pod.UID, cID1, true)
  573. verifyUpdates(t, m, 0)
  574. if status, ok := m.GetPodStatus(pod.UID); ok {
  575. t.Errorf("Unexpected PodStatus: %+v", status)
  576. }
  577. t.Log("Setting initial status.")
  578. m.SetPodStatus(pod, status)
  579. verifyUpdates(t, m, 1)
  580. status = expectPodStatus(t, m, pod)
  581. verifyReadiness("initial", &status, false, false, false)
  582. t.Log("Setting unchanged readiness should do nothing.")
  583. m.SetContainerReadiness(pod.UID, cID1, false)
  584. verifyUpdates(t, m, 0)
  585. status = expectPodStatus(t, m, pod)
  586. verifyReadiness("unchanged", &status, false, false, false)
  587. t.Log("Setting container readiness should generate update but not pod readiness.")
  588. m.SetContainerReadiness(pod.UID, cID1, true)
  589. verifyUpdates(t, m, 1)
  590. status = expectPodStatus(t, m, pod)
  591. verifyReadiness("c1 ready", &status, true, false, false)
  592. t.Log("Setting both containers to ready should update pod readiness.")
  593. m.SetContainerReadiness(pod.UID, cID2, true)
  594. verifyUpdates(t, m, 1)
  595. status = expectPodStatus(t, m, pod)
  596. verifyReadiness("all ready", &status, true, true, true)
  597. t.Log("Setting non-existent container readiness should fail.")
  598. m.SetContainerReadiness(pod.UID, kubecontainer.ContainerID{Type: "test", ID: "foo"}, true)
  599. verifyUpdates(t, m, 0)
  600. status = expectPodStatus(t, m, pod)
  601. verifyReadiness("ignore non-existent", &status, true, true, true)
  602. }
  603. func TestSetContainerStartup(t *testing.T) {
  604. cID1 := kubecontainer.ContainerID{Type: "test", ID: "1"}
  605. cID2 := kubecontainer.ContainerID{Type: "test", ID: "2"}
  606. containerStatuses := []v1.ContainerStatus{
  607. {
  608. Name: "c1",
  609. ContainerID: cID1.String(),
  610. Ready: false,
  611. }, {
  612. Name: "c2",
  613. ContainerID: cID2.String(),
  614. Ready: false,
  615. },
  616. }
  617. status := v1.PodStatus{
  618. ContainerStatuses: containerStatuses,
  619. Conditions: []v1.PodCondition{{
  620. Type: v1.PodReady,
  621. Status: v1.ConditionFalse,
  622. }},
  623. }
  624. pod := getTestPod()
  625. pod.Spec.Containers = []v1.Container{{Name: "c1"}, {Name: "c2"}}
  626. // Verify expected startup of containers & pod.
  627. verifyStartup := func(step string, status *v1.PodStatus, c1Started, c2Started, podStarted bool) {
  628. for _, c := range status.ContainerStatuses {
  629. switch c.ContainerID {
  630. case cID1.String():
  631. if (c.Started != nil && *c.Started) != c1Started {
  632. t.Errorf("[%s] Expected startup of c1 to be %v but was %v", step, c1Started, c.Started)
  633. }
  634. case cID2.String():
  635. if (c.Started != nil && *c.Started) != c2Started {
  636. t.Errorf("[%s] Expected startup of c2 to be %v but was %v", step, c2Started, c.Started)
  637. }
  638. default:
  639. t.Fatalf("[%s] Unexpected container: %+v", step, c)
  640. }
  641. }
  642. }
  643. m := newTestManager(&fake.Clientset{})
  644. // Add test pod because the container spec has been changed.
  645. m.podManager.AddPod(pod)
  646. t.Log("Setting startup before status should fail.")
  647. m.SetContainerStartup(pod.UID, cID1, true)
  648. verifyUpdates(t, m, 0)
  649. if status, ok := m.GetPodStatus(pod.UID); ok {
  650. t.Errorf("Unexpected PodStatus: %+v", status)
  651. }
  652. t.Log("Setting initial status.")
  653. m.SetPodStatus(pod, status)
  654. verifyUpdates(t, m, 1)
  655. status = expectPodStatus(t, m, pod)
  656. verifyStartup("initial", &status, false, false, false)
  657. t.Log("Setting unchanged startup should do nothing.")
  658. m.SetContainerStartup(pod.UID, cID1, false)
  659. verifyUpdates(t, m, 1)
  660. status = expectPodStatus(t, m, pod)
  661. verifyStartup("unchanged", &status, false, false, false)
  662. t.Log("Setting container startup should generate update but not pod startup.")
  663. m.SetContainerStartup(pod.UID, cID1, true)
  664. verifyUpdates(t, m, 1) // Started = nil to false
  665. status = expectPodStatus(t, m, pod)
  666. verifyStartup("c1 ready", &status, true, false, false)
  667. t.Log("Setting both containers to ready should update pod startup.")
  668. m.SetContainerStartup(pod.UID, cID2, true)
  669. verifyUpdates(t, m, 1)
  670. status = expectPodStatus(t, m, pod)
  671. verifyStartup("all ready", &status, true, true, true)
  672. t.Log("Setting non-existent container startup should fail.")
  673. m.SetContainerStartup(pod.UID, kubecontainer.ContainerID{Type: "test", ID: "foo"}, true)
  674. verifyUpdates(t, m, 0)
  675. status = expectPodStatus(t, m, pod)
  676. verifyStartup("ignore non-existent", &status, true, true, true)
  677. }
  678. func TestSyncBatchCleanupVersions(t *testing.T) {
  679. m := newTestManager(&fake.Clientset{})
  680. testPod := getTestPod()
  681. mirrorPod := getTestPod()
  682. mirrorPod.UID = "mirror-uid"
  683. mirrorPod.Name = "mirror_pod"
  684. mirrorPod.Annotations = map[string]string{
  685. kubetypes.ConfigSourceAnnotationKey: "api",
  686. kubetypes.ConfigMirrorAnnotationKey: "mirror",
  687. }
  688. t.Logf("Orphaned pods should be removed.")
  689. m.apiStatusVersions[kubetypes.MirrorPodUID(testPod.UID)] = 100
  690. m.apiStatusVersions[kubetypes.MirrorPodUID(mirrorPod.UID)] = 200
  691. m.syncBatch()
  692. if _, ok := m.apiStatusVersions[kubetypes.MirrorPodUID(testPod.UID)]; ok {
  693. t.Errorf("Should have cleared status for testPod")
  694. }
  695. if _, ok := m.apiStatusVersions[kubetypes.MirrorPodUID(mirrorPod.UID)]; ok {
  696. t.Errorf("Should have cleared status for mirrorPod")
  697. }
  698. t.Logf("Non-orphaned pods should not be removed.")
  699. m.SetPodStatus(testPod, getRandomPodStatus())
  700. m.podManager.AddPod(mirrorPod)
  701. staticPod := mirrorPod
  702. staticPod.UID = "static-uid"
  703. staticPod.Annotations = map[string]string{kubetypes.ConfigSourceAnnotationKey: "file"}
  704. m.podManager.AddPod(staticPod)
  705. m.apiStatusVersions[kubetypes.MirrorPodUID(testPod.UID)] = 100
  706. m.apiStatusVersions[kubetypes.MirrorPodUID(mirrorPod.UID)] = 200
  707. m.testSyncBatch()
  708. if _, ok := m.apiStatusVersions[kubetypes.MirrorPodUID(testPod.UID)]; !ok {
  709. t.Errorf("Should not have cleared status for testPod")
  710. }
  711. if _, ok := m.apiStatusVersions[kubetypes.MirrorPodUID(mirrorPod.UID)]; !ok {
  712. t.Errorf("Should not have cleared status for mirrorPod")
  713. }
  714. }
  715. func TestReconcilePodStatus(t *testing.T) {
  716. testPod := getTestPod()
  717. client := fake.NewSimpleClientset(testPod)
  718. syncer := newTestManager(client)
  719. syncer.SetPodStatus(testPod, getRandomPodStatus())
  720. t.Logf("Call syncBatch directly to test reconcile")
  721. syncer.syncBatch() // The apiStatusVersions should be set now
  722. client.ClearActions()
  723. podStatus, ok := syncer.GetPodStatus(testPod.UID)
  724. if !ok {
  725. t.Fatalf("Should find pod status for pod: %#v", testPod)
  726. }
  727. testPod.Status = podStatus
  728. t.Logf("If the pod status is the same, a reconciliation is not needed and syncBatch should do nothing")
  729. syncer.podManager.UpdatePod(testPod)
  730. if syncer.needsReconcile(testPod.UID, podStatus) {
  731. t.Errorf("Pod status is the same, a reconciliation is not needed")
  732. }
  733. syncer.syncBatch()
  734. verifyActions(t, syncer, []core.Action{})
  735. // If the pod status is the same, only the timestamp is in Rfc3339 format (lower precision without nanosecond),
  736. // a reconciliation is not needed, syncBatch should do nothing.
  737. // The StartTime should have been set in SetPodStatus().
  738. // This test is done because the related issue #15262/PR #15263 to move apiserver to RFC339NANO is closed.
  739. t.Logf("Syncbatch should do nothing, as a reconciliation is not required")
  740. normalizedStartTime := testPod.Status.StartTime.Rfc3339Copy()
  741. testPod.Status.StartTime = &normalizedStartTime
  742. syncer.podManager.UpdatePod(testPod)
  743. if syncer.needsReconcile(testPod.UID, podStatus) {
  744. t.Errorf("Pod status only differs for timestamp format, a reconciliation is not needed")
  745. }
  746. syncer.syncBatch()
  747. verifyActions(t, syncer, []core.Action{})
  748. t.Logf("If the pod status is different, a reconciliation is needed, syncBatch should trigger an update")
  749. testPod.Status = getRandomPodStatus()
  750. syncer.podManager.UpdatePod(testPod)
  751. if !syncer.needsReconcile(testPod.UID, podStatus) {
  752. t.Errorf("Pod status is different, a reconciliation is needed")
  753. }
  754. syncer.syncBatch()
  755. verifyActions(t, syncer, []core.Action{getAction(), patchAction()})
  756. }
  757. func expectPodStatus(t *testing.T, m *manager, pod *v1.Pod) v1.PodStatus {
  758. status, ok := m.GetPodStatus(pod.UID)
  759. if !ok {
  760. t.Fatalf("Expected PodStatus for %q not found", pod.UID)
  761. }
  762. return status
  763. }
  764. func TestDeletePods(t *testing.T) {
  765. pod := getTestPod()
  766. t.Logf("Set the deletion timestamp.")
  767. pod.DeletionTimestamp = &metav1.Time{Time: time.Now()}
  768. client := fake.NewSimpleClientset(pod)
  769. m := newTestManager(client)
  770. m.podManager.AddPod(pod)
  771. status := getRandomPodStatus()
  772. now := metav1.Now()
  773. status.StartTime = &now
  774. m.SetPodStatus(pod, status)
  775. t.Logf("Expect to see a delete action.")
  776. verifyActions(t, m, []core.Action{getAction(), patchAction(), deleteAction()})
  777. }
  778. func TestDoNotDeleteMirrorPods(t *testing.T) {
  779. staticPod := getTestPod()
  780. staticPod.Annotations = map[string]string{kubetypes.ConfigSourceAnnotationKey: "file"}
  781. mirrorPod := getTestPod()
  782. mirrorPod.UID = "mirror-12345678"
  783. mirrorPod.Annotations = map[string]string{
  784. kubetypes.ConfigSourceAnnotationKey: "api",
  785. kubetypes.ConfigMirrorAnnotationKey: "mirror",
  786. }
  787. t.Logf("Set the deletion timestamp.")
  788. mirrorPod.DeletionTimestamp = &metav1.Time{Time: time.Now()}
  789. client := fake.NewSimpleClientset(mirrorPod)
  790. m := newTestManager(client)
  791. m.podManager.AddPod(staticPod)
  792. m.podManager.AddPod(mirrorPod)
  793. t.Logf("Verify setup.")
  794. assert.True(t, kubetypes.IsStaticPod(staticPod), "SetUp error: staticPod")
  795. assert.True(t, kubetypes.IsMirrorPod(mirrorPod), "SetUp error: mirrorPod")
  796. assert.Equal(t, m.podManager.TranslatePodUID(mirrorPod.UID), kubetypes.ResolvedPodUID(staticPod.UID))
  797. status := getRandomPodStatus()
  798. now := metav1.Now()
  799. status.StartTime = &now
  800. m.SetPodStatus(staticPod, status)
  801. t.Logf("Expect not to see a delete action.")
  802. verifyActions(t, m, []core.Action{getAction(), patchAction()})
  803. }
  804. func TestUpdateLastTransitionTime(t *testing.T) {
  805. old := metav1.Now()
  806. for desc, test := range map[string]struct {
  807. condition *v1.PodCondition
  808. oldCondition *v1.PodCondition
  809. expectUpdate bool
  810. }{
  811. "should do nothing if no corresponding condition": {
  812. expectUpdate: false,
  813. },
  814. "should update last transition time if no old condition": {
  815. condition: &v1.PodCondition{
  816. Type: "test-type",
  817. Status: v1.ConditionTrue,
  818. },
  819. oldCondition: nil,
  820. expectUpdate: true,
  821. },
  822. "should update last transition time if condition is changed": {
  823. condition: &v1.PodCondition{
  824. Type: "test-type",
  825. Status: v1.ConditionTrue,
  826. },
  827. oldCondition: &v1.PodCondition{
  828. Type: "test-type",
  829. Status: v1.ConditionFalse,
  830. LastTransitionTime: old,
  831. },
  832. expectUpdate: true,
  833. },
  834. "should keep last transition time if condition is not changed": {
  835. condition: &v1.PodCondition{
  836. Type: "test-type",
  837. Status: v1.ConditionFalse,
  838. },
  839. oldCondition: &v1.PodCondition{
  840. Type: "test-type",
  841. Status: v1.ConditionFalse,
  842. LastTransitionTime: old,
  843. },
  844. expectUpdate: false,
  845. },
  846. } {
  847. t.Logf("TestCase %q", desc)
  848. status := &v1.PodStatus{}
  849. oldStatus := &v1.PodStatus{}
  850. if test.condition != nil {
  851. status.Conditions = []v1.PodCondition{*test.condition}
  852. }
  853. if test.oldCondition != nil {
  854. oldStatus.Conditions = []v1.PodCondition{*test.oldCondition}
  855. }
  856. updateLastTransitionTime(status, oldStatus, "test-type")
  857. if test.expectUpdate {
  858. assert.True(t, status.Conditions[0].LastTransitionTime.After(old.Time))
  859. } else if test.condition != nil {
  860. assert.Equal(t, old, status.Conditions[0].LastTransitionTime)
  861. }
  862. }
  863. }
  864. func getAction() core.GetAction {
  865. return core.GetActionImpl{ActionImpl: core.ActionImpl{Verb: "get", Resource: schema.GroupVersionResource{Resource: "pods"}}}
  866. }
  867. func patchAction() core.PatchAction {
  868. return core.PatchActionImpl{ActionImpl: core.ActionImpl{Verb: "patch", Resource: schema.GroupVersionResource{Resource: "pods"}, Subresource: "status"}}
  869. }
  870. func deleteAction() core.DeleteAction {
  871. return core.DeleteActionImpl{ActionImpl: core.ActionImpl{Verb: "delete", Resource: schema.GroupVersionResource{Resource: "pods"}}}
  872. }
  873. func TestMergePodStatus(t *testing.T) {
  874. useCases := []struct {
  875. desc string
  876. oldPodStatus func(input v1.PodStatus) v1.PodStatus
  877. newPodStatus func(input v1.PodStatus) v1.PodStatus
  878. expectPodStatus v1.PodStatus
  879. }{
  880. {
  881. "no change",
  882. func(input v1.PodStatus) v1.PodStatus { return input },
  883. func(input v1.PodStatus) v1.PodStatus { return input },
  884. getPodStatus(),
  885. },
  886. {
  887. "readiness changes",
  888. func(input v1.PodStatus) v1.PodStatus { return input },
  889. func(input v1.PodStatus) v1.PodStatus {
  890. input.Conditions[0].Status = v1.ConditionFalse
  891. return input
  892. },
  893. v1.PodStatus{
  894. Phase: v1.PodRunning,
  895. Conditions: []v1.PodCondition{
  896. {
  897. Type: v1.PodReady,
  898. Status: v1.ConditionFalse,
  899. },
  900. {
  901. Type: v1.PodScheduled,
  902. Status: v1.ConditionTrue,
  903. },
  904. },
  905. Message: "Message",
  906. },
  907. },
  908. {
  909. "additional pod condition",
  910. func(input v1.PodStatus) v1.PodStatus {
  911. input.Conditions = append(input.Conditions, v1.PodCondition{
  912. Type: v1.PodConditionType("example.com/feature"),
  913. Status: v1.ConditionTrue,
  914. })
  915. return input
  916. },
  917. func(input v1.PodStatus) v1.PodStatus { return input },
  918. v1.PodStatus{
  919. Phase: v1.PodRunning,
  920. Conditions: []v1.PodCondition{
  921. {
  922. Type: v1.PodReady,
  923. Status: v1.ConditionTrue,
  924. },
  925. {
  926. Type: v1.PodScheduled,
  927. Status: v1.ConditionTrue,
  928. },
  929. {
  930. Type: v1.PodConditionType("example.com/feature"),
  931. Status: v1.ConditionTrue,
  932. },
  933. },
  934. Message: "Message",
  935. },
  936. },
  937. {
  938. "additional pod condition and readiness changes",
  939. func(input v1.PodStatus) v1.PodStatus {
  940. input.Conditions = append(input.Conditions, v1.PodCondition{
  941. Type: v1.PodConditionType("example.com/feature"),
  942. Status: v1.ConditionTrue,
  943. })
  944. return input
  945. },
  946. func(input v1.PodStatus) v1.PodStatus {
  947. input.Conditions[0].Status = v1.ConditionFalse
  948. return input
  949. },
  950. v1.PodStatus{
  951. Phase: v1.PodRunning,
  952. Conditions: []v1.PodCondition{
  953. {
  954. Type: v1.PodReady,
  955. Status: v1.ConditionFalse,
  956. },
  957. {
  958. Type: v1.PodScheduled,
  959. Status: v1.ConditionTrue,
  960. },
  961. {
  962. Type: v1.PodConditionType("example.com/feature"),
  963. Status: v1.ConditionTrue,
  964. },
  965. },
  966. Message: "Message",
  967. },
  968. },
  969. {
  970. "additional pod condition changes",
  971. func(input v1.PodStatus) v1.PodStatus {
  972. input.Conditions = append(input.Conditions, v1.PodCondition{
  973. Type: v1.PodConditionType("example.com/feature"),
  974. Status: v1.ConditionTrue,
  975. })
  976. return input
  977. },
  978. func(input v1.PodStatus) v1.PodStatus {
  979. input.Conditions = append(input.Conditions, v1.PodCondition{
  980. Type: v1.PodConditionType("example.com/feature"),
  981. Status: v1.ConditionFalse,
  982. })
  983. return input
  984. },
  985. v1.PodStatus{
  986. Phase: v1.PodRunning,
  987. Conditions: []v1.PodCondition{
  988. {
  989. Type: v1.PodReady,
  990. Status: v1.ConditionTrue,
  991. },
  992. {
  993. Type: v1.PodScheduled,
  994. Status: v1.ConditionTrue,
  995. },
  996. {
  997. Type: v1.PodConditionType("example.com/feature"),
  998. Status: v1.ConditionTrue,
  999. },
  1000. },
  1001. Message: "Message",
  1002. },
  1003. },
  1004. }
  1005. for _, tc := range useCases {
  1006. output := mergePodStatus(tc.oldPodStatus(getPodStatus()), tc.newPodStatus(getPodStatus()))
  1007. if !conditionsEqual(output.Conditions, tc.expectPodStatus.Conditions) || !statusEqual(output, tc.expectPodStatus) {
  1008. t.Errorf("test case %q failed, expect: %+v, got %+v", tc.desc, tc.expectPodStatus, output)
  1009. }
  1010. }
  1011. }
  1012. func statusEqual(left, right v1.PodStatus) bool {
  1013. left.Conditions = nil
  1014. right.Conditions = nil
  1015. return reflect.DeepEqual(left, right)
  1016. }
  1017. func conditionsEqual(left, right []v1.PodCondition) bool {
  1018. if len(left) != len(right) {
  1019. return false
  1020. }
  1021. for _, l := range left {
  1022. found := false
  1023. for _, r := range right {
  1024. if l.Type == r.Type {
  1025. found = true
  1026. if l.Status != r.Status {
  1027. return false
  1028. }
  1029. }
  1030. }
  1031. if !found {
  1032. return false
  1033. }
  1034. }
  1035. return true
  1036. }
  1037. func getPodStatus() v1.PodStatus {
  1038. return v1.PodStatus{
  1039. Phase: v1.PodRunning,
  1040. Conditions: []v1.PodCondition{
  1041. {
  1042. Type: v1.PodReady,
  1043. Status: v1.ConditionTrue,
  1044. },
  1045. {
  1046. Type: v1.PodScheduled,
  1047. Status: v1.ConditionTrue,
  1048. },
  1049. },
  1050. Message: "Message",
  1051. }
  1052. }