kuberuntime_container_test.go 9.7 KB

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