kuberuntime_container_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*
  2. Copyright 2016 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 kuberuntime
  14. import (
  15. "path/filepath"
  16. "strings"
  17. "testing"
  18. "time"
  19. "github.com/stretchr/testify/assert"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/api/core/v1"
  22. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  23. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  24. containertest "k8s.io/kubernetes/pkg/kubelet/container/testing"
  25. "k8s.io/kubernetes/pkg/kubelet/lifecycle"
  26. )
  27. // TestRemoveContainer tests removing the container and its corresponding container logs.
  28. func TestRemoveContainer(t *testing.T) {
  29. fakeRuntime, _, m, err := createTestRuntimeManager()
  30. pod := &v1.Pod{
  31. ObjectMeta: metav1.ObjectMeta{
  32. UID: "12345678",
  33. Name: "bar",
  34. Namespace: "new",
  35. },
  36. Spec: v1.PodSpec{
  37. Containers: []v1.Container{
  38. {
  39. Name: "foo",
  40. Image: "busybox",
  41. ImagePullPolicy: v1.PullIfNotPresent,
  42. },
  43. },
  44. },
  45. }
  46. // Create fake sandbox and container
  47. _, fakeContainers := makeAndSetFakePod(t, m, fakeRuntime, pod)
  48. assert.Equal(t, len(fakeContainers), 1)
  49. containerID := fakeContainers[0].Id
  50. fakeOS := m.osInterface.(*containertest.FakeOS)
  51. err = m.removeContainer(containerID)
  52. assert.NoError(t, err)
  53. // Verify container log is removed
  54. expectedContainerLogPath := filepath.Join(podLogsRootDirectory, "new_bar_12345678", "foo", "0.log")
  55. expectedContainerLogSymlink := legacyLogSymlink(containerID, "foo", "bar", "new")
  56. assert.Equal(t, fakeOS.Removes, []string{expectedContainerLogPath, expectedContainerLogSymlink})
  57. // Verify container is removed
  58. assert.Contains(t, fakeRuntime.Called, "RemoveContainer")
  59. containers, err := fakeRuntime.ListContainers(&runtimeapi.ContainerFilter{Id: containerID})
  60. assert.NoError(t, err)
  61. assert.Empty(t, containers)
  62. }
  63. // TestKillContainer tests killing the container in a Pod.
  64. func TestKillContainer(t *testing.T) {
  65. _, _, m, _ := createTestRuntimeManager()
  66. tests := []struct {
  67. caseName string
  68. pod *v1.Pod
  69. containerID kubecontainer.ContainerID
  70. containerName string
  71. reason string
  72. gracePeriodOverride int64
  73. succeed bool
  74. }{
  75. {
  76. caseName: "Failed to find container in pods, expect to return error",
  77. pod: &v1.Pod{
  78. ObjectMeta: metav1.ObjectMeta{UID: "pod1_id", Name: "pod1", Namespace: "default"},
  79. Spec: v1.PodSpec{Containers: []v1.Container{{Name: "empty_container"}}},
  80. },
  81. containerID: kubecontainer.ContainerID{Type: "docker", ID: "not_exist_container_id"},
  82. containerName: "not_exist_container",
  83. reason: "unknown reason",
  84. gracePeriodOverride: 0,
  85. succeed: false,
  86. },
  87. }
  88. for _, test := range tests {
  89. err := m.killContainer(test.pod, test.containerID, test.containerName, test.reason, &test.gracePeriodOverride)
  90. if test.succeed != (err == nil) {
  91. t.Errorf("%s: expected %v, got %v (%v)", test.caseName, test.succeed, (err == nil), err)
  92. }
  93. }
  94. }
  95. // TestToKubeContainerStatus tests the converting the CRI container status to
  96. // the internal type (i.e., toKubeContainerStatus()) for containers in
  97. // different states.
  98. func TestToKubeContainerStatus(t *testing.T) {
  99. cid := &kubecontainer.ContainerID{Type: "testRuntime", ID: "dummyid"}
  100. meta := &runtimeapi.ContainerMetadata{Name: "cname", Attempt: 3}
  101. imageSpec := &runtimeapi.ImageSpec{Image: "fimage"}
  102. var (
  103. createdAt int64 = 327
  104. startedAt int64 = 999
  105. finishedAt int64 = 1278
  106. )
  107. for desc, test := range map[string]struct {
  108. input *runtimeapi.ContainerStatus
  109. expected *kubecontainer.ContainerStatus
  110. }{
  111. "created container": {
  112. input: &runtimeapi.ContainerStatus{
  113. Id: cid.ID,
  114. Metadata: meta,
  115. Image: imageSpec,
  116. State: runtimeapi.ContainerState_CONTAINER_CREATED,
  117. CreatedAt: createdAt,
  118. },
  119. expected: &kubecontainer.ContainerStatus{
  120. ID: *cid,
  121. Image: imageSpec.Image,
  122. State: kubecontainer.ContainerStateCreated,
  123. CreatedAt: time.Unix(0, createdAt),
  124. },
  125. },
  126. "running container": {
  127. input: &runtimeapi.ContainerStatus{
  128. Id: cid.ID,
  129. Metadata: meta,
  130. Image: imageSpec,
  131. State: runtimeapi.ContainerState_CONTAINER_RUNNING,
  132. CreatedAt: createdAt,
  133. StartedAt: startedAt,
  134. },
  135. expected: &kubecontainer.ContainerStatus{
  136. ID: *cid,
  137. Image: imageSpec.Image,
  138. State: kubecontainer.ContainerStateRunning,
  139. CreatedAt: time.Unix(0, createdAt),
  140. StartedAt: time.Unix(0, startedAt),
  141. },
  142. },
  143. "exited container": {
  144. input: &runtimeapi.ContainerStatus{
  145. Id: cid.ID,
  146. Metadata: meta,
  147. Image: imageSpec,
  148. State: runtimeapi.ContainerState_CONTAINER_EXITED,
  149. CreatedAt: createdAt,
  150. StartedAt: startedAt,
  151. FinishedAt: finishedAt,
  152. ExitCode: int32(121),
  153. Reason: "GotKilled",
  154. Message: "The container was killed",
  155. },
  156. expected: &kubecontainer.ContainerStatus{
  157. ID: *cid,
  158. Image: imageSpec.Image,
  159. State: kubecontainer.ContainerStateExited,
  160. CreatedAt: time.Unix(0, createdAt),
  161. StartedAt: time.Unix(0, startedAt),
  162. FinishedAt: time.Unix(0, finishedAt),
  163. ExitCode: 121,
  164. Reason: "GotKilled",
  165. Message: "The container was killed",
  166. },
  167. },
  168. "unknown container": {
  169. input: &runtimeapi.ContainerStatus{
  170. Id: cid.ID,
  171. Metadata: meta,
  172. Image: imageSpec,
  173. State: runtimeapi.ContainerState_CONTAINER_UNKNOWN,
  174. CreatedAt: createdAt,
  175. StartedAt: startedAt,
  176. },
  177. expected: &kubecontainer.ContainerStatus{
  178. ID: *cid,
  179. Image: imageSpec.Image,
  180. State: kubecontainer.ContainerStateUnknown,
  181. CreatedAt: time.Unix(0, createdAt),
  182. StartedAt: time.Unix(0, startedAt),
  183. },
  184. },
  185. } {
  186. actual := toKubeContainerStatus(test.input, cid.Type)
  187. assert.Equal(t, test.expected, actual, desc)
  188. }
  189. }
  190. func TestLifeCycleHook(t *testing.T) {
  191. // Setup
  192. fakeRuntime, _, m, _ := createTestRuntimeManager()
  193. gracePeriod := int64(30)
  194. cID := kubecontainer.ContainerID{
  195. Type: "docker",
  196. ID: "foo",
  197. }
  198. testPod := &v1.Pod{
  199. ObjectMeta: metav1.ObjectMeta{
  200. Name: "bar",
  201. Namespace: "default",
  202. },
  203. Spec: v1.PodSpec{
  204. Containers: []v1.Container{
  205. {
  206. Name: "foo",
  207. Image: "busybox",
  208. ImagePullPolicy: v1.PullIfNotPresent,
  209. Command: []string{"testCommand"},
  210. WorkingDir: "testWorkingDir",
  211. },
  212. },
  213. },
  214. }
  215. cmdPostStart := &v1.Lifecycle{
  216. PostStart: &v1.Handler{
  217. Exec: &v1.ExecAction{
  218. Command: []string{"PostStartCMD"},
  219. },
  220. },
  221. }
  222. httpLifeCycle := &v1.Lifecycle{
  223. PreStop: &v1.Handler{
  224. HTTPGet: &v1.HTTPGetAction{
  225. Host: "testHost.com",
  226. Path: "/GracefulExit",
  227. },
  228. },
  229. }
  230. cmdLifeCycle := &v1.Lifecycle{
  231. PreStop: &v1.Handler{
  232. Exec: &v1.ExecAction{
  233. Command: []string{"PreStopCMD"},
  234. },
  235. },
  236. }
  237. fakeRunner := &containertest.FakeContainerCommandRunner{}
  238. fakeHTTP := &fakeHTTP{}
  239. lcHanlder := lifecycle.NewHandlerRunner(
  240. fakeHTTP,
  241. fakeRunner,
  242. nil)
  243. m.runner = lcHanlder
  244. // Configured and works as expected
  245. t.Run("PreStop-CMDExec", func(t *testing.T) {
  246. testPod.Spec.Containers[0].Lifecycle = cmdLifeCycle
  247. m.killContainer(testPod, cID, "foo", "testKill", &gracePeriod)
  248. if fakeRunner.Cmd[0] != cmdLifeCycle.PreStop.Exec.Command[0] {
  249. t.Errorf("CMD Prestop hook was not invoked")
  250. }
  251. })
  252. // Configured and working HTTP hook
  253. t.Run("PreStop-HTTPGet", func(t *testing.T) {
  254. defer func() { fakeHTTP.url = "" }()
  255. testPod.Spec.Containers[0].Lifecycle = httpLifeCycle
  256. m.killContainer(testPod, cID, "foo", "testKill", &gracePeriod)
  257. if !strings.Contains(fakeHTTP.url, httpLifeCycle.PreStop.HTTPGet.Host) {
  258. t.Errorf("HTTP Prestop hook was not invoked")
  259. }
  260. })
  261. // When there is no time to run PreStopHook
  262. t.Run("PreStop-NoTimeToRun", func(t *testing.T) {
  263. gracePeriodLocal := int64(0)
  264. testPod.DeletionGracePeriodSeconds = &gracePeriodLocal
  265. testPod.Spec.TerminationGracePeriodSeconds = &gracePeriodLocal
  266. m.killContainer(testPod, cID, "foo", "testKill", &gracePeriodLocal)
  267. if strings.Contains(fakeHTTP.url, httpLifeCycle.PreStop.HTTPGet.Host) {
  268. t.Errorf("HTTP Should not execute when gracePeriod is 0")
  269. }
  270. })
  271. // Post Start script
  272. t.Run("PostStart-CmdExe", func(t *testing.T) {
  273. // Fake all the things you need before trying to create a container
  274. fakeSandBox, _ := makeAndSetFakePod(t, m, fakeRuntime, testPod)
  275. fakeSandBoxConfig, _ := m.generatePodSandboxConfig(testPod, 0)
  276. testPod.Spec.Containers[0].Lifecycle = cmdPostStart
  277. testContainer := &testPod.Spec.Containers[0]
  278. fakePodStatus := &kubecontainer.PodStatus{
  279. ContainerStatuses: []*kubecontainer.ContainerStatus{
  280. {
  281. ID: kubecontainer.ContainerID{
  282. Type: "docker",
  283. ID: testContainer.Name,
  284. },
  285. Name: testContainer.Name,
  286. State: kubecontainer.ContainerStateCreated,
  287. CreatedAt: time.Unix(0, time.Now().Unix()),
  288. },
  289. },
  290. }
  291. // Now try to create a container, which should in turn invoke PostStart Hook
  292. _, err := m.startContainer(fakeSandBox.Id, fakeSandBoxConfig, testContainer, testPod, fakePodStatus, nil, "")
  293. if err != nil {
  294. t.Errorf("startContainer erro =%v", err)
  295. }
  296. if fakeRunner.Cmd[0] != cmdPostStart.PostStart.Exec.Command[0] {
  297. t.Errorf("CMD PostStart hook was not invoked")
  298. }
  299. })
  300. }