generic_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /*
  2. Copyright 2015 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 pleg
  14. import (
  15. "errors"
  16. "fmt"
  17. "reflect"
  18. "sort"
  19. "testing"
  20. "time"
  21. "github.com/stretchr/testify/assert"
  22. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  23. containertest "k8s.io/kubernetes/pkg/kubelet/container/testing"
  24. "k8s.io/kubernetes/pkg/types"
  25. "k8s.io/kubernetes/pkg/util/clock"
  26. "k8s.io/kubernetes/pkg/util/diff"
  27. )
  28. const (
  29. testContainerRuntimeType = "fooRuntime"
  30. )
  31. type TestGenericPLEG struct {
  32. pleg *GenericPLEG
  33. runtime *containertest.FakeRuntime
  34. clock *clock.FakeClock
  35. }
  36. func newTestGenericPLEG() *TestGenericPLEG {
  37. fakeRuntime := &containertest.FakeRuntime{}
  38. clock := clock.NewFakeClock(time.Time{})
  39. // The channel capacity should be large enough to hold all events in a
  40. // single test.
  41. pleg := &GenericPLEG{
  42. relistPeriod: time.Hour,
  43. runtime: fakeRuntime,
  44. eventChannel: make(chan *PodLifecycleEvent, 100),
  45. podRecords: make(podRecords),
  46. clock: clock,
  47. }
  48. return &TestGenericPLEG{pleg: pleg, runtime: fakeRuntime, clock: clock}
  49. }
  50. func getEventsFromChannel(ch <-chan *PodLifecycleEvent) []*PodLifecycleEvent {
  51. events := []*PodLifecycleEvent{}
  52. for len(ch) > 0 {
  53. e := <-ch
  54. events = append(events, e)
  55. }
  56. return events
  57. }
  58. func createTestContainer(ID string, state kubecontainer.ContainerState) *kubecontainer.Container {
  59. return &kubecontainer.Container{
  60. ID: kubecontainer.ContainerID{Type: testContainerRuntimeType, ID: ID},
  61. State: state,
  62. }
  63. }
  64. type sortableEvents []*PodLifecycleEvent
  65. func (a sortableEvents) Len() int { return len(a) }
  66. func (a sortableEvents) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  67. func (a sortableEvents) Less(i, j int) bool {
  68. if a[i].ID != a[j].ID {
  69. return a[i].ID < a[j].ID
  70. }
  71. return a[i].Data.(string) < a[j].Data.(string)
  72. }
  73. func verifyEvents(t *testing.T, expected, actual []*PodLifecycleEvent) {
  74. sort.Sort(sortableEvents(expected))
  75. sort.Sort(sortableEvents(actual))
  76. if !reflect.DeepEqual(expected, actual) {
  77. t.Errorf("Actual events differ from the expected; diff:\n %v", diff.ObjectDiff(expected, actual))
  78. }
  79. }
  80. func TestRelisting(t *testing.T) {
  81. testPleg := newTestGenericPLEG()
  82. pleg, runtime := testPleg.pleg, testPleg.runtime
  83. ch := pleg.Watch()
  84. // The first relist should send a PodSync event to each pod.
  85. runtime.AllPodList = []*containertest.FakePod{
  86. {Pod: &kubecontainer.Pod{
  87. ID: "1234",
  88. Containers: []*kubecontainer.Container{
  89. createTestContainer("c1", kubecontainer.ContainerStateExited),
  90. createTestContainer("c2", kubecontainer.ContainerStateRunning),
  91. createTestContainer("c3", kubecontainer.ContainerStateUnknown),
  92. },
  93. }},
  94. {Pod: &kubecontainer.Pod{
  95. ID: "4567",
  96. Containers: []*kubecontainer.Container{
  97. createTestContainer("c1", kubecontainer.ContainerStateExited),
  98. },
  99. }},
  100. }
  101. pleg.relist()
  102. // Report every running/exited container if we see them for the first time.
  103. expected := []*PodLifecycleEvent{
  104. {ID: "1234", Type: ContainerStarted, Data: "c2"},
  105. {ID: "4567", Type: ContainerDied, Data: "c1"},
  106. {ID: "1234", Type: ContainerDied, Data: "c1"},
  107. }
  108. actual := getEventsFromChannel(ch)
  109. verifyEvents(t, expected, actual)
  110. // The second relist should not send out any event because no container
  111. // changed.
  112. pleg.relist()
  113. verifyEvents(t, expected, actual)
  114. runtime.AllPodList = []*containertest.FakePod{
  115. {Pod: &kubecontainer.Pod{
  116. ID: "1234",
  117. Containers: []*kubecontainer.Container{
  118. createTestContainer("c2", kubecontainer.ContainerStateExited),
  119. createTestContainer("c3", kubecontainer.ContainerStateRunning),
  120. },
  121. }},
  122. {Pod: &kubecontainer.Pod{
  123. ID: "4567",
  124. Containers: []*kubecontainer.Container{
  125. createTestContainer("c4", kubecontainer.ContainerStateRunning),
  126. },
  127. }},
  128. }
  129. pleg.relist()
  130. // Only report containers that transitioned to running or exited status.
  131. expected = []*PodLifecycleEvent{
  132. {ID: "1234", Type: ContainerRemoved, Data: "c1"},
  133. {ID: "1234", Type: ContainerDied, Data: "c2"},
  134. {ID: "1234", Type: ContainerStarted, Data: "c3"},
  135. {ID: "4567", Type: ContainerRemoved, Data: "c1"},
  136. {ID: "4567", Type: ContainerStarted, Data: "c4"},
  137. }
  138. actual = getEventsFromChannel(ch)
  139. verifyEvents(t, expected, actual)
  140. }
  141. func TestDetectingContainerDeaths(t *testing.T) {
  142. // Vary the number of relists after the container started and before the
  143. // container died to account for the changes in pleg's internal states.
  144. testReportMissingContainers(t, 1)
  145. testReportMissingPods(t, 1)
  146. testReportMissingContainers(t, 3)
  147. testReportMissingPods(t, 3)
  148. }
  149. func testReportMissingContainers(t *testing.T, numRelists int) {
  150. testPleg := newTestGenericPLEG()
  151. pleg, runtime := testPleg.pleg, testPleg.runtime
  152. ch := pleg.Watch()
  153. runtime.AllPodList = []*containertest.FakePod{
  154. {Pod: &kubecontainer.Pod{
  155. ID: "1234",
  156. Containers: []*kubecontainer.Container{
  157. createTestContainer("c1", kubecontainer.ContainerStateRunning),
  158. createTestContainer("c2", kubecontainer.ContainerStateRunning),
  159. createTestContainer("c3", kubecontainer.ContainerStateExited),
  160. },
  161. }},
  162. }
  163. // Relist and drain the events from the channel.
  164. for i := 0; i < numRelists; i++ {
  165. pleg.relist()
  166. getEventsFromChannel(ch)
  167. }
  168. // Container c2 was stopped and removed between relists. We should report
  169. // the event. The exited container c3 was garbage collected (i.e., removed)
  170. // between relists. We should ignore that event.
  171. runtime.AllPodList = []*containertest.FakePod{
  172. {Pod: &kubecontainer.Pod{
  173. ID: "1234",
  174. Containers: []*kubecontainer.Container{
  175. createTestContainer("c1", kubecontainer.ContainerStateRunning),
  176. },
  177. }},
  178. }
  179. pleg.relist()
  180. expected := []*PodLifecycleEvent{
  181. {ID: "1234", Type: ContainerDied, Data: "c2"},
  182. {ID: "1234", Type: ContainerRemoved, Data: "c2"},
  183. {ID: "1234", Type: ContainerRemoved, Data: "c3"},
  184. }
  185. actual := getEventsFromChannel(ch)
  186. verifyEvents(t, expected, actual)
  187. }
  188. func testReportMissingPods(t *testing.T, numRelists int) {
  189. testPleg := newTestGenericPLEG()
  190. pleg, runtime := testPleg.pleg, testPleg.runtime
  191. ch := pleg.Watch()
  192. runtime.AllPodList = []*containertest.FakePod{
  193. {Pod: &kubecontainer.Pod{
  194. ID: "1234",
  195. Containers: []*kubecontainer.Container{
  196. createTestContainer("c2", kubecontainer.ContainerStateRunning),
  197. },
  198. }},
  199. }
  200. // Relist and drain the events from the channel.
  201. for i := 0; i < numRelists; i++ {
  202. pleg.relist()
  203. getEventsFromChannel(ch)
  204. }
  205. // Container c2 was stopped and removed between relists. We should report
  206. // the event.
  207. runtime.AllPodList = []*containertest.FakePod{}
  208. pleg.relist()
  209. expected := []*PodLifecycleEvent{
  210. {ID: "1234", Type: ContainerDied, Data: "c2"},
  211. {ID: "1234", Type: ContainerRemoved, Data: "c2"},
  212. }
  213. actual := getEventsFromChannel(ch)
  214. verifyEvents(t, expected, actual)
  215. }
  216. func newTestGenericPLEGWithRuntimeMock() (*GenericPLEG, *containertest.Mock) {
  217. runtimeMock := &containertest.Mock{}
  218. pleg := &GenericPLEG{
  219. relistPeriod: time.Hour,
  220. runtime: runtimeMock,
  221. eventChannel: make(chan *PodLifecycleEvent, 100),
  222. podRecords: make(podRecords),
  223. cache: kubecontainer.NewCache(),
  224. clock: clock.RealClock{},
  225. }
  226. return pleg, runtimeMock
  227. }
  228. func createTestPodsStatusesAndEvents(num int) ([]*kubecontainer.Pod, []*kubecontainer.PodStatus, []*PodLifecycleEvent) {
  229. var pods []*kubecontainer.Pod
  230. var statuses []*kubecontainer.PodStatus
  231. var events []*PodLifecycleEvent
  232. for i := 0; i < num; i++ {
  233. id := types.UID(fmt.Sprintf("test-pod-%d", i))
  234. cState := kubecontainer.ContainerStateRunning
  235. container := createTestContainer(fmt.Sprintf("c%d", i), cState)
  236. pod := &kubecontainer.Pod{
  237. ID: id,
  238. Containers: []*kubecontainer.Container{container},
  239. }
  240. status := &kubecontainer.PodStatus{
  241. ID: id,
  242. ContainerStatuses: []*kubecontainer.ContainerStatus{{ID: container.ID, State: cState}},
  243. }
  244. event := &PodLifecycleEvent{ID: pod.ID, Type: ContainerStarted, Data: container.ID.ID}
  245. pods = append(pods, pod)
  246. statuses = append(statuses, status)
  247. events = append(events, event)
  248. }
  249. return pods, statuses, events
  250. }
  251. func TestRelistWithCache(t *testing.T) {
  252. pleg, runtimeMock := newTestGenericPLEGWithRuntimeMock()
  253. ch := pleg.Watch()
  254. pods, statuses, events := createTestPodsStatusesAndEvents(2)
  255. runtimeMock.On("GetPods", true).Return(pods, nil)
  256. runtimeMock.On("GetPodStatus", pods[0].ID, "", "").Return(statuses[0], nil).Once()
  257. // Inject an error when querying runtime for the pod status for pods[1].
  258. statusErr := fmt.Errorf("unable to get status")
  259. runtimeMock.On("GetPodStatus", pods[1].ID, "", "").Return(&kubecontainer.PodStatus{}, statusErr).Once()
  260. pleg.relist()
  261. actualEvents := getEventsFromChannel(ch)
  262. cases := []struct {
  263. pod *kubecontainer.Pod
  264. status *kubecontainer.PodStatus
  265. error error
  266. }{
  267. {pod: pods[0], status: statuses[0], error: nil},
  268. {pod: pods[1], status: &kubecontainer.PodStatus{}, error: statusErr},
  269. }
  270. for i, c := range cases {
  271. testStr := fmt.Sprintf("test[%d]", i)
  272. actualStatus, actualErr := pleg.cache.Get(c.pod.ID)
  273. assert.Equal(t, c.status, actualStatus, testStr)
  274. assert.Equal(t, c.error, actualErr, testStr)
  275. }
  276. // pleg should not generate any event for pods[1] because of the error.
  277. assert.Exactly(t, []*PodLifecycleEvent{events[0]}, actualEvents)
  278. // Return normal status for pods[1].
  279. runtimeMock.On("GetPodStatus", pods[1].ID, "", "").Return(statuses[1], nil).Once()
  280. pleg.relist()
  281. actualEvents = getEventsFromChannel(ch)
  282. cases = []struct {
  283. pod *kubecontainer.Pod
  284. status *kubecontainer.PodStatus
  285. error error
  286. }{
  287. {pod: pods[0], status: statuses[0], error: nil},
  288. {pod: pods[1], status: statuses[1], error: nil},
  289. }
  290. for i, c := range cases {
  291. testStr := fmt.Sprintf("test[%d]", i)
  292. actualStatus, actualErr := pleg.cache.Get(c.pod.ID)
  293. assert.Equal(t, c.status, actualStatus, testStr)
  294. assert.Equal(t, c.error, actualErr, testStr)
  295. }
  296. // Now that we are able to query status for pods[1], pleg should generate an event.
  297. assert.Exactly(t, []*PodLifecycleEvent{events[1]}, actualEvents)
  298. }
  299. func TestRemoveCacheEntry(t *testing.T) {
  300. pleg, runtimeMock := newTestGenericPLEGWithRuntimeMock()
  301. pods, statuses, _ := createTestPodsStatusesAndEvents(1)
  302. runtimeMock.On("GetPods", true).Return(pods, nil).Once()
  303. runtimeMock.On("GetPodStatus", pods[0].ID, "", "").Return(statuses[0], nil).Once()
  304. // Does a relist to populate the cache.
  305. pleg.relist()
  306. // Delete the pod from runtime. Verify that the cache entry has been
  307. // removed after relisting.
  308. runtimeMock.On("GetPods", true).Return([]*kubecontainer.Pod{}, nil).Once()
  309. pleg.relist()
  310. actualStatus, actualErr := pleg.cache.Get(pods[0].ID)
  311. assert.Equal(t, &kubecontainer.PodStatus{ID: pods[0].ID}, actualStatus)
  312. assert.Equal(t, nil, actualErr)
  313. }
  314. func TestHealthy(t *testing.T) {
  315. testPleg := newTestGenericPLEG()
  316. pleg, _, clock := testPleg.pleg, testPleg.runtime, testPleg.clock
  317. ok, _ := pleg.Healthy()
  318. assert.True(t, ok, "pleg should be healthy")
  319. // Advance the clock without any relisting.
  320. clock.Step(time.Minute * 10)
  321. ok, _ = pleg.Healthy()
  322. assert.False(t, ok, "pleg should be unhealthy")
  323. // Relist and than advance the time by 1 minute. pleg should be healthy
  324. // because this is within the allowed limit.
  325. pleg.relist()
  326. clock.Step(time.Minute * 1)
  327. ok, _ = pleg.Healthy()
  328. assert.True(t, ok, "pleg should be healthy")
  329. }
  330. func TestRelistWithReinspection(t *testing.T) {
  331. pleg, runtimeMock := newTestGenericPLEGWithRuntimeMock()
  332. ch := pleg.Watch()
  333. infraContainer := createTestContainer("infra", kubecontainer.ContainerStateRunning)
  334. podID := types.UID("test-pod")
  335. pods := []*kubecontainer.Pod{{
  336. ID: podID,
  337. Containers: []*kubecontainer.Container{infraContainer},
  338. }}
  339. runtimeMock.On("GetPods", true).Return(pods, nil).Once()
  340. goodStatus := &kubecontainer.PodStatus{
  341. ID: podID,
  342. ContainerStatuses: []*kubecontainer.ContainerStatus{{ID: infraContainer.ID, State: infraContainer.State}},
  343. }
  344. runtimeMock.On("GetPodStatus", podID, "", "").Return(goodStatus, nil).Once()
  345. goodEvent := &PodLifecycleEvent{ID: podID, Type: ContainerStarted, Data: infraContainer.ID.ID}
  346. // listing 1 - everything ok, infra container set up for pod
  347. pleg.relist()
  348. actualEvents := getEventsFromChannel(ch)
  349. actualStatus, actualErr := pleg.cache.Get(podID)
  350. assert.Equal(t, goodStatus, actualStatus)
  351. assert.Equal(t, nil, actualErr)
  352. assert.Exactly(t, []*PodLifecycleEvent{goodEvent}, actualEvents)
  353. // listing 2 - pretend runtime was in the middle of creating the non-infra container for the pod
  354. // and return an error during inspection
  355. transientContainer := createTestContainer("transient", kubecontainer.ContainerStateUnknown)
  356. podsWithTransientContainer := []*kubecontainer.Pod{{
  357. ID: podID,
  358. Containers: []*kubecontainer.Container{infraContainer, transientContainer},
  359. }}
  360. runtimeMock.On("GetPods", true).Return(podsWithTransientContainer, nil).Once()
  361. badStatus := &kubecontainer.PodStatus{
  362. ID: podID,
  363. ContainerStatuses: []*kubecontainer.ContainerStatus{},
  364. }
  365. runtimeMock.On("GetPodStatus", podID, "", "").Return(badStatus, errors.New("inspection error")).Once()
  366. pleg.relist()
  367. actualEvents = getEventsFromChannel(ch)
  368. actualStatus, actualErr = pleg.cache.Get(podID)
  369. assert.Equal(t, badStatus, actualStatus)
  370. assert.Equal(t, errors.New("inspection error"), actualErr)
  371. assert.Exactly(t, []*PodLifecycleEvent{}, actualEvents)
  372. // listing 3 - pretend the transient container has now disappeared, leaving just the infra
  373. // container. Make sure the pod is reinspected for its status and the cache is updated.
  374. runtimeMock.On("GetPods", true).Return(pods, nil).Once()
  375. runtimeMock.On("GetPodStatus", podID, "", "").Return(goodStatus, nil).Once()
  376. pleg.relist()
  377. actualEvents = getEventsFromChannel(ch)
  378. actualStatus, actualErr = pleg.cache.Get(podID)
  379. assert.Equal(t, goodStatus, actualStatus)
  380. assert.Equal(t, nil, actualErr)
  381. // no events are expected because relist #1 set the old pod record which has the infra container
  382. // running. relist #2 had the inspection error and therefore didn't modify either old or new.
  383. // relist #3 forced the reinspection of the pod to retrieve its status, but because the list of
  384. // containers was the same as relist #1, nothing "changed", so there are no new events.
  385. assert.Exactly(t, []*PodLifecycleEvent{}, actualEvents)
  386. }