pods.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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 common
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "golang.org/x/net/websocket"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/labels"
  25. "k8s.io/apimachinery/pkg/runtime"
  26. "k8s.io/apimachinery/pkg/types"
  27. "k8s.io/apimachinery/pkg/util/intstr"
  28. "k8s.io/apimachinery/pkg/util/uuid"
  29. "k8s.io/apimachinery/pkg/util/wait"
  30. "k8s.io/apimachinery/pkg/watch"
  31. "k8s.io/client-go/tools/cache"
  32. watchtools "k8s.io/client-go/tools/watch"
  33. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  34. "k8s.io/kubernetes/pkg/kubelet"
  35. "k8s.io/kubernetes/test/e2e/framework"
  36. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  37. imageutils "k8s.io/kubernetes/test/utils/image"
  38. "github.com/onsi/ginkgo"
  39. "github.com/onsi/gomega"
  40. )
  41. var (
  42. buildBackOffDuration = time.Minute
  43. syncLoopFrequency = 10 * time.Second
  44. maxBackOffTolerance = time.Duration(1.3 * float64(kubelet.MaxContainerBackOff))
  45. // maxReadyStatusUpdateTolerance specifies the latency that allows kubelet to update pod status.
  46. // When kubelet is under heavy load (tests may be parallelized), the delay may be longer, hence
  47. // causing tests to be flaky.
  48. maxReadyStatusUpdateTolerance = 10 * time.Second
  49. )
  50. // testHostIP tests that a pod gets a host IP
  51. func testHostIP(podClient *framework.PodClient, pod *v1.Pod) {
  52. ginkgo.By("creating pod")
  53. podClient.CreateSync(pod)
  54. // Try to make sure we get a hostIP for each pod.
  55. hostIPTimeout := 2 * time.Minute
  56. t := time.Now()
  57. for {
  58. p, err := podClient.Get(pod.Name, metav1.GetOptions{})
  59. framework.ExpectNoError(err, "Failed to get pod %q", pod.Name)
  60. if p.Status.HostIP != "" {
  61. e2elog.Logf("Pod %s has hostIP: %s", p.Name, p.Status.HostIP)
  62. break
  63. }
  64. if time.Since(t) >= hostIPTimeout {
  65. framework.Failf("Gave up waiting for hostIP of pod %s after %v seconds",
  66. p.Name, time.Since(t).Seconds())
  67. }
  68. e2elog.Logf("Retrying to get the hostIP of pod %s", p.Name)
  69. time.Sleep(5 * time.Second)
  70. }
  71. }
  72. func startPodAndGetBackOffs(podClient *framework.PodClient, pod *v1.Pod, sleepAmount time.Duration) (time.Duration, time.Duration) {
  73. podClient.CreateSync(pod)
  74. time.Sleep(sleepAmount)
  75. gomega.Expect(pod.Spec.Containers).NotTo(gomega.BeEmpty())
  76. podName := pod.Name
  77. containerName := pod.Spec.Containers[0].Name
  78. ginkgo.By("getting restart delay-0")
  79. _, err := getRestartDelay(podClient, podName, containerName)
  80. if err != nil {
  81. framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
  82. }
  83. ginkgo.By("getting restart delay-1")
  84. delay1, err := getRestartDelay(podClient, podName, containerName)
  85. if err != nil {
  86. framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
  87. }
  88. ginkgo.By("getting restart delay-2")
  89. delay2, err := getRestartDelay(podClient, podName, containerName)
  90. if err != nil {
  91. framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
  92. }
  93. return delay1, delay2
  94. }
  95. func getRestartDelay(podClient *framework.PodClient, podName string, containerName string) (time.Duration, error) {
  96. beginTime := time.Now()
  97. var previousRestartCount int32 = -1
  98. var previousFinishedAt time.Time
  99. for time.Since(beginTime) < (2 * maxBackOffTolerance) { // may just miss the 1st MaxContainerBackOff delay
  100. time.Sleep(time.Second)
  101. pod, err := podClient.Get(podName, metav1.GetOptions{})
  102. framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", podName))
  103. status, ok := podutil.GetContainerStatus(pod.Status.ContainerStatuses, containerName)
  104. if !ok {
  105. e2elog.Logf("getRestartDelay: status missing")
  106. continue
  107. }
  108. // the only case this happens is if this is the first time the Pod is running and there is no "Last State".
  109. if status.LastTerminationState.Terminated == nil {
  110. e2elog.Logf("Container's last state is not \"Terminated\".")
  111. continue
  112. }
  113. if previousRestartCount == -1 {
  114. if status.State.Running != nil {
  115. // container is still Running, there is no "FinishedAt" time.
  116. continue
  117. } else if status.State.Terminated != nil {
  118. previousFinishedAt = status.State.Terminated.FinishedAt.Time
  119. } else {
  120. previousFinishedAt = status.LastTerminationState.Terminated.FinishedAt.Time
  121. }
  122. previousRestartCount = status.RestartCount
  123. }
  124. // when the RestartCount is changed, the Containers will be in one of the following states:
  125. //Running, Terminated, Waiting (it already is waiting for the backoff period to expire, and the last state details have been stored into status.LastTerminationState).
  126. if status.RestartCount > previousRestartCount {
  127. var startedAt time.Time
  128. if status.State.Running != nil {
  129. startedAt = status.State.Running.StartedAt.Time
  130. } else if status.State.Terminated != nil {
  131. startedAt = status.State.Terminated.StartedAt.Time
  132. } else {
  133. startedAt = status.LastTerminationState.Terminated.StartedAt.Time
  134. }
  135. e2elog.Logf("getRestartDelay: restartCount = %d, finishedAt=%s restartedAt=%s (%s)", status.RestartCount, previousFinishedAt, startedAt, startedAt.Sub(previousFinishedAt))
  136. return startedAt.Sub(previousFinishedAt), nil
  137. }
  138. }
  139. return 0, fmt.Errorf("timeout getting pod restart delay")
  140. }
  141. var _ = framework.KubeDescribe("Pods", func() {
  142. f := framework.NewDefaultFramework("pods")
  143. var podClient *framework.PodClient
  144. ginkgo.BeforeEach(func() {
  145. podClient = f.PodClient()
  146. })
  147. /*
  148. Release : v1.9
  149. Testname: Pods, assigned hostip
  150. Description: Create a Pod. Pod status MUST return successfully and contains a valid IP address.
  151. */
  152. framework.ConformanceIt("should get a host IP [NodeConformance]", func() {
  153. name := "pod-hostip-" + string(uuid.NewUUID())
  154. testHostIP(podClient, &v1.Pod{
  155. ObjectMeta: metav1.ObjectMeta{
  156. Name: name,
  157. },
  158. Spec: v1.PodSpec{
  159. Containers: []v1.Container{
  160. {
  161. Name: "test",
  162. Image: imageutils.GetPauseImageName(),
  163. },
  164. },
  165. },
  166. })
  167. })
  168. /*
  169. Release : v1.9
  170. Testname: Pods, lifecycle
  171. Description: A Pod is created with a unique label. Pod MUST be accessible when queried using the label selector upon creation. Add a watch, check if the Pod is running. Pod then deleted, The pod deletion timestamp is observed. The watch MUST return the pod deleted event. Query with the original selector for the Pod MUST return empty list.
  172. */
  173. framework.ConformanceIt("should be submitted and removed [NodeConformance]", func() {
  174. ginkgo.By("creating the pod")
  175. name := "pod-submit-remove-" + string(uuid.NewUUID())
  176. value := strconv.Itoa(time.Now().Nanosecond())
  177. pod := &v1.Pod{
  178. ObjectMeta: metav1.ObjectMeta{
  179. Name: name,
  180. Labels: map[string]string{
  181. "name": "foo",
  182. "time": value,
  183. },
  184. },
  185. Spec: v1.PodSpec{
  186. Containers: []v1.Container{
  187. {
  188. Name: "nginx",
  189. Image: imageutils.GetE2EImage(imageutils.Nginx),
  190. },
  191. },
  192. },
  193. }
  194. ginkgo.By("setting up watch")
  195. selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  196. options := metav1.ListOptions{LabelSelector: selector.String()}
  197. pods, err := podClient.List(options)
  198. framework.ExpectNoError(err, "failed to query for pods")
  199. gomega.Expect(len(pods.Items)).To(gomega.Equal(0))
  200. options = metav1.ListOptions{
  201. LabelSelector: selector.String(),
  202. ResourceVersion: pods.ListMeta.ResourceVersion,
  203. }
  204. listCompleted := make(chan bool, 1)
  205. lw := &cache.ListWatch{
  206. ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
  207. options.LabelSelector = selector.String()
  208. podList, err := podClient.List(options)
  209. if err == nil {
  210. select {
  211. case listCompleted <- true:
  212. e2elog.Logf("observed the pod list")
  213. return podList, err
  214. default:
  215. e2elog.Logf("channel blocked")
  216. }
  217. }
  218. return podList, err
  219. },
  220. WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
  221. options.LabelSelector = selector.String()
  222. return podClient.Watch(options)
  223. },
  224. }
  225. _, _, w, _ := watchtools.NewIndexerInformerWatcher(lw, &v1.Pod{})
  226. defer w.Stop()
  227. ginkgo.By("submitting the pod to kubernetes")
  228. podClient.Create(pod)
  229. ginkgo.By("verifying the pod is in kubernetes")
  230. selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  231. options = metav1.ListOptions{LabelSelector: selector.String()}
  232. pods, err = podClient.List(options)
  233. framework.ExpectNoError(err, "failed to query for pods")
  234. gomega.Expect(len(pods.Items)).To(gomega.Equal(1))
  235. ginkgo.By("verifying pod creation was observed")
  236. select {
  237. case <-listCompleted:
  238. select {
  239. case event, _ := <-w.ResultChan():
  240. if event.Type != watch.Added {
  241. framework.Failf("Failed to observe pod creation: %v", event)
  242. }
  243. case <-time.After(framework.PodStartTimeout):
  244. framework.Failf("Timeout while waiting for pod creation")
  245. }
  246. case <-time.After(10 * time.Second):
  247. framework.Failf("Timeout while waiting to observe pod list")
  248. }
  249. // We need to wait for the pod to be running, otherwise the deletion
  250. // may be carried out immediately rather than gracefully.
  251. framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
  252. // save the running pod
  253. pod, err = podClient.Get(pod.Name, metav1.GetOptions{})
  254. framework.ExpectNoError(err, "failed to GET scheduled pod")
  255. ginkgo.By("deleting the pod gracefully")
  256. err = podClient.Delete(pod.Name, metav1.NewDeleteOptions(30))
  257. framework.ExpectNoError(err, "failed to delete pod")
  258. ginkgo.By("verifying the kubelet observed the termination notice")
  259. gomega.Expect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {
  260. podList, err := framework.GetKubeletPods(f.ClientSet, pod.Spec.NodeName)
  261. if err != nil {
  262. e2elog.Logf("Unable to retrieve kubelet pods for node %v: %v", pod.Spec.NodeName, err)
  263. return false, nil
  264. }
  265. for _, kubeletPod := range podList.Items {
  266. if pod.Name != kubeletPod.Name {
  267. continue
  268. }
  269. if kubeletPod.ObjectMeta.DeletionTimestamp == nil {
  270. e2elog.Logf("deletion has not yet been observed")
  271. return false, nil
  272. }
  273. return true, nil
  274. }
  275. e2elog.Logf("no pod exists with the name we were looking for, assuming the termination request was observed and completed")
  276. return true, nil
  277. })).NotTo(gomega.HaveOccurred(), "kubelet never observed the termination notice")
  278. ginkgo.By("verifying pod deletion was observed")
  279. deleted := false
  280. var lastPod *v1.Pod
  281. timer := time.After(framework.DefaultPodDeletionTimeout)
  282. for !deleted {
  283. select {
  284. case event, _ := <-w.ResultChan():
  285. switch event.Type {
  286. case watch.Deleted:
  287. lastPod = event.Object.(*v1.Pod)
  288. deleted = true
  289. case watch.Error:
  290. e2elog.Logf("received a watch error: %v", event.Object)
  291. framework.Failf("watch closed with error")
  292. }
  293. case <-timer:
  294. framework.Failf("timed out waiting for pod deletion")
  295. }
  296. }
  297. if !deleted {
  298. framework.Failf("Failed to observe pod deletion")
  299. }
  300. gomega.Expect(lastPod.DeletionTimestamp).ToNot(gomega.BeNil())
  301. gomega.Expect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(gomega.BeZero())
  302. selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  303. options = metav1.ListOptions{LabelSelector: selector.String()}
  304. pods, err = podClient.List(options)
  305. framework.ExpectNoError(err, "failed to query for pods")
  306. gomega.Expect(len(pods.Items)).To(gomega.Equal(0))
  307. })
  308. /*
  309. Release : v1.9
  310. Testname: Pods, update
  311. Description: Create a Pod with a unique label. Query for the Pod with the label as selector MUST be successful. Update the pod to change the value of the Label. Query for the Pod with the new value for the label MUST be successful.
  312. */
  313. framework.ConformanceIt("should be updated [NodeConformance]", func() {
  314. ginkgo.By("creating the pod")
  315. name := "pod-update-" + string(uuid.NewUUID())
  316. value := strconv.Itoa(time.Now().Nanosecond())
  317. pod := &v1.Pod{
  318. ObjectMeta: metav1.ObjectMeta{
  319. Name: name,
  320. Labels: map[string]string{
  321. "name": "foo",
  322. "time": value,
  323. },
  324. },
  325. Spec: v1.PodSpec{
  326. Containers: []v1.Container{
  327. {
  328. Name: "nginx",
  329. Image: imageutils.GetE2EImage(imageutils.Nginx),
  330. },
  331. },
  332. },
  333. }
  334. ginkgo.By("submitting the pod to kubernetes")
  335. pod = podClient.CreateSync(pod)
  336. ginkgo.By("verifying the pod is in kubernetes")
  337. selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  338. options := metav1.ListOptions{LabelSelector: selector.String()}
  339. pods, err := podClient.List(options)
  340. framework.ExpectNoError(err, "failed to query for pods")
  341. gomega.Expect(len(pods.Items)).To(gomega.Equal(1))
  342. ginkgo.By("updating the pod")
  343. podClient.Update(name, func(pod *v1.Pod) {
  344. value = strconv.Itoa(time.Now().Nanosecond())
  345. pod.Labels["time"] = value
  346. })
  347. framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
  348. ginkgo.By("verifying the updated pod is in kubernetes")
  349. selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  350. options = metav1.ListOptions{LabelSelector: selector.String()}
  351. pods, err = podClient.List(options)
  352. framework.ExpectNoError(err, "failed to query for pods")
  353. gomega.Expect(len(pods.Items)).To(gomega.Equal(1))
  354. e2elog.Logf("Pod update OK")
  355. })
  356. /*
  357. Release : v1.9
  358. Testname: Pods, ActiveDeadlineSeconds
  359. Description: Create a Pod with a unique label. Query for the Pod with the label as selector MUST be successful. The Pod is updated with ActiveDeadlineSeconds set on the Pod spec. Pod MUST terminate of the specified time elapses.
  360. */
  361. framework.ConformanceIt("should allow activeDeadlineSeconds to be updated [NodeConformance]", func() {
  362. ginkgo.By("creating the pod")
  363. name := "pod-update-activedeadlineseconds-" + string(uuid.NewUUID())
  364. value := strconv.Itoa(time.Now().Nanosecond())
  365. pod := &v1.Pod{
  366. ObjectMeta: metav1.ObjectMeta{
  367. Name: name,
  368. Labels: map[string]string{
  369. "name": "foo",
  370. "time": value,
  371. },
  372. },
  373. Spec: v1.PodSpec{
  374. Containers: []v1.Container{
  375. {
  376. Name: "nginx",
  377. Image: imageutils.GetE2EImage(imageutils.Nginx),
  378. },
  379. },
  380. },
  381. }
  382. ginkgo.By("submitting the pod to kubernetes")
  383. podClient.CreateSync(pod)
  384. ginkgo.By("verifying the pod is in kubernetes")
  385. selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  386. options := metav1.ListOptions{LabelSelector: selector.String()}
  387. pods, err := podClient.List(options)
  388. framework.ExpectNoError(err, "failed to query for pods")
  389. gomega.Expect(len(pods.Items)).To(gomega.Equal(1))
  390. ginkgo.By("updating the pod")
  391. podClient.Update(name, func(pod *v1.Pod) {
  392. newDeadline := int64(5)
  393. pod.Spec.ActiveDeadlineSeconds = &newDeadline
  394. })
  395. framework.ExpectNoError(f.WaitForPodTerminated(pod.Name, "DeadlineExceeded"))
  396. })
  397. /*
  398. Release : v1.9
  399. Testname: Pods, service environment variables
  400. Description: Create a server Pod listening on port 9376. A Service called fooservice is created for the server Pod listening on port 8765 targeting port 8080. If a new Pod is created in the cluster then the Pod MUST have the fooservice environment variables available from this new Pod. The new create Pod MUST have environment variables such as FOOSERVICE_SERVICE_HOST, FOOSERVICE_SERVICE_PORT, FOOSERVICE_PORT, FOOSERVICE_PORT_8765_TCP_PORT, FOOSERVICE_PORT_8765_TCP_PROTO, FOOSERVICE_PORT_8765_TCP and FOOSERVICE_PORT_8765_TCP_ADDR that are populated with proper values.
  401. */
  402. framework.ConformanceIt("should contain environment variables for services [NodeConformance]", func() {
  403. // Make a pod that will be a service.
  404. // This pod serves its hostname via HTTP.
  405. serverName := "server-envvars-" + string(uuid.NewUUID())
  406. serverPod := &v1.Pod{
  407. ObjectMeta: metav1.ObjectMeta{
  408. Name: serverName,
  409. Labels: map[string]string{"name": serverName},
  410. },
  411. Spec: v1.PodSpec{
  412. Containers: []v1.Container{
  413. {
  414. Name: "srv",
  415. Image: framework.ServeHostnameImage,
  416. Ports: []v1.ContainerPort{{ContainerPort: 9376}},
  417. },
  418. },
  419. },
  420. }
  421. podClient.CreateSync(serverPod)
  422. // This service exposes port 8080 of the test pod as a service on port 8765
  423. // TODO(filbranden): We would like to use a unique service name such as:
  424. // svcName := "svc-envvars-" + randomSuffix()
  425. // However, that affects the name of the environment variables which are the capitalized
  426. // service name, so that breaks this test. One possibility is to tweak the variable names
  427. // to match the service. Another is to rethink environment variable names and possibly
  428. // allow overriding the prefix in the service manifest.
  429. svcName := "fooservice"
  430. svc := &v1.Service{
  431. ObjectMeta: metav1.ObjectMeta{
  432. Name: svcName,
  433. Labels: map[string]string{
  434. "name": svcName,
  435. },
  436. },
  437. Spec: v1.ServiceSpec{
  438. Ports: []v1.ServicePort{{
  439. Port: 8765,
  440. TargetPort: intstr.FromInt(8080),
  441. }},
  442. Selector: map[string]string{
  443. "name": serverName,
  444. },
  445. },
  446. }
  447. _, err := f.ClientSet.CoreV1().Services(f.Namespace.Name).Create(svc)
  448. framework.ExpectNoError(err, "failed to create service")
  449. // Make a client pod that verifies that it has the service environment variables.
  450. podName := "client-envvars-" + string(uuid.NewUUID())
  451. const containerName = "env3cont"
  452. pod := &v1.Pod{
  453. ObjectMeta: metav1.ObjectMeta{
  454. Name: podName,
  455. Labels: map[string]string{"name": podName},
  456. },
  457. Spec: v1.PodSpec{
  458. Containers: []v1.Container{
  459. {
  460. Name: containerName,
  461. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  462. Command: []string{"sh", "-c", "env"},
  463. },
  464. },
  465. RestartPolicy: v1.RestartPolicyNever,
  466. },
  467. }
  468. // It's possible for the Pod to be created before the Kubelet is updated with the new
  469. // service. In that case, we just retry.
  470. const maxRetries = 3
  471. expectedVars := []string{
  472. "FOOSERVICE_SERVICE_HOST=",
  473. "FOOSERVICE_SERVICE_PORT=",
  474. "FOOSERVICE_PORT=",
  475. "FOOSERVICE_PORT_8765_TCP_PORT=",
  476. "FOOSERVICE_PORT_8765_TCP_PROTO=",
  477. "FOOSERVICE_PORT_8765_TCP=",
  478. "FOOSERVICE_PORT_8765_TCP_ADDR=",
  479. }
  480. framework.ExpectNoErrorWithRetries(func() error {
  481. return f.MatchContainerOutput(pod, containerName, expectedVars, gomega.ContainSubstring)
  482. }, maxRetries, "Container should have service environment variables set")
  483. })
  484. /*
  485. Release : v1.13
  486. Testname: Pods, remote command execution over websocket
  487. Description: A Pod is created. Websocket is created to retrieve exec command output from this pod.
  488. Message retrieved form Websocket MUST match with expected exec command output.
  489. */
  490. framework.ConformanceIt("should support remote command execution over websockets [NodeConformance]", func() {
  491. config, err := framework.LoadConfig()
  492. framework.ExpectNoError(err, "unable to get base config")
  493. ginkgo.By("creating the pod")
  494. name := "pod-exec-websocket-" + string(uuid.NewUUID())
  495. pod := &v1.Pod{
  496. ObjectMeta: metav1.ObjectMeta{
  497. Name: name,
  498. },
  499. Spec: v1.PodSpec{
  500. Containers: []v1.Container{
  501. {
  502. Name: "main",
  503. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  504. Command: []string{"/bin/sh", "-c", "echo container is alive; sleep 600"},
  505. },
  506. },
  507. },
  508. }
  509. ginkgo.By("submitting the pod to kubernetes")
  510. pod = podClient.CreateSync(pod)
  511. req := f.ClientSet.CoreV1().RESTClient().Get().
  512. Namespace(f.Namespace.Name).
  513. Resource("pods").
  514. Name(pod.Name).
  515. Suffix("exec").
  516. Param("stderr", "1").
  517. Param("stdout", "1").
  518. Param("container", pod.Spec.Containers[0].Name).
  519. Param("command", "echo").
  520. Param("command", "remote execution test")
  521. url := req.URL()
  522. ws, err := framework.OpenWebSocketForURL(url, config, []string{"channel.k8s.io"})
  523. if err != nil {
  524. framework.Failf("Failed to open websocket to %s: %v", url.String(), err)
  525. }
  526. defer ws.Close()
  527. buf := &bytes.Buffer{}
  528. gomega.Eventually(func() error {
  529. for {
  530. var msg []byte
  531. if err := websocket.Message.Receive(ws, &msg); err != nil {
  532. if err == io.EOF {
  533. break
  534. }
  535. framework.Failf("Failed to read completely from websocket %s: %v", url.String(), err)
  536. }
  537. if len(msg) == 0 {
  538. continue
  539. }
  540. if msg[0] != 1 {
  541. if len(msg) == 1 {
  542. // skip an empty message on stream other than stdout
  543. continue
  544. } else {
  545. framework.Failf("Got message from server that didn't start with channel 1 (STDOUT): %v", msg)
  546. }
  547. }
  548. buf.Write(msg[1:])
  549. }
  550. if buf.Len() == 0 {
  551. return fmt.Errorf("Unexpected output from server")
  552. }
  553. if !strings.Contains(buf.String(), "remote execution test") {
  554. return fmt.Errorf("Expected to find 'remote execution test' in %q", buf.String())
  555. }
  556. return nil
  557. }, time.Minute, 10*time.Second).Should(gomega.BeNil())
  558. })
  559. /*
  560. Release : v1.13
  561. Testname: Pods, logs from websockets
  562. Description: A Pod is created. Websocket is created to retrieve log of a container from this pod.
  563. Message retrieved form Websocket MUST match with container's output.
  564. */
  565. framework.ConformanceIt("should support retrieving logs from the container over websockets [NodeConformance]", func() {
  566. config, err := framework.LoadConfig()
  567. framework.ExpectNoError(err, "unable to get base config")
  568. ginkgo.By("creating the pod")
  569. name := "pod-logs-websocket-" + string(uuid.NewUUID())
  570. pod := &v1.Pod{
  571. ObjectMeta: metav1.ObjectMeta{
  572. Name: name,
  573. },
  574. Spec: v1.PodSpec{
  575. Containers: []v1.Container{
  576. {
  577. Name: "main",
  578. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  579. Command: []string{"/bin/sh", "-c", "echo container is alive; sleep 10000"},
  580. },
  581. },
  582. },
  583. }
  584. ginkgo.By("submitting the pod to kubernetes")
  585. podClient.CreateSync(pod)
  586. req := f.ClientSet.CoreV1().RESTClient().Get().
  587. Namespace(f.Namespace.Name).
  588. Resource("pods").
  589. Name(pod.Name).
  590. Suffix("log").
  591. Param("container", pod.Spec.Containers[0].Name)
  592. url := req.URL()
  593. ws, err := framework.OpenWebSocketForURL(url, config, []string{"binary.k8s.io"})
  594. if err != nil {
  595. framework.Failf("Failed to open websocket to %s: %v", url.String(), err)
  596. }
  597. defer ws.Close()
  598. buf := &bytes.Buffer{}
  599. for {
  600. var msg []byte
  601. if err := websocket.Message.Receive(ws, &msg); err != nil {
  602. if err == io.EOF {
  603. break
  604. }
  605. framework.Failf("Failed to read completely from websocket %s: %v", url.String(), err)
  606. }
  607. if len(strings.TrimSpace(string(msg))) == 0 {
  608. continue
  609. }
  610. buf.Write(msg)
  611. }
  612. if buf.String() != "container is alive\n" {
  613. framework.Failf("Unexpected websocket logs:\n%s", buf.String())
  614. }
  615. })
  616. // Slow (~7 mins)
  617. ginkgo.It("should have their auto-restart back-off timer reset on image update [Slow][NodeConformance]", func() {
  618. podName := "pod-back-off-image"
  619. containerName := "back-off"
  620. pod := &v1.Pod{
  621. ObjectMeta: metav1.ObjectMeta{
  622. Name: podName,
  623. Labels: map[string]string{"test": "back-off-image"},
  624. },
  625. Spec: v1.PodSpec{
  626. Containers: []v1.Container{
  627. {
  628. Name: containerName,
  629. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  630. Command: []string{"/bin/sh", "-c", "sleep 5", "/crash/missing"},
  631. },
  632. },
  633. },
  634. }
  635. delay1, delay2 := startPodAndGetBackOffs(podClient, pod, buildBackOffDuration)
  636. ginkgo.By("updating the image")
  637. podClient.Update(podName, func(pod *v1.Pod) {
  638. pod.Spec.Containers[0].Image = imageutils.GetE2EImage(imageutils.Nginx)
  639. })
  640. time.Sleep(syncLoopFrequency)
  641. framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
  642. ginkgo.By("get restart delay after image update")
  643. delayAfterUpdate, err := getRestartDelay(podClient, podName, containerName)
  644. if err != nil {
  645. framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
  646. }
  647. if delayAfterUpdate > 2*delay2 || delayAfterUpdate > 2*delay1 {
  648. framework.Failf("updating image did not reset the back-off value in pod=%s/%s d3=%s d2=%s d1=%s", podName, containerName, delayAfterUpdate, delay1, delay2)
  649. }
  650. })
  651. // Slow by design (~27 mins) issue #19027
  652. ginkgo.It("should cap back-off at MaxContainerBackOff [Slow][NodeConformance]", func() {
  653. podName := "back-off-cap"
  654. containerName := "back-off-cap"
  655. pod := &v1.Pod{
  656. ObjectMeta: metav1.ObjectMeta{
  657. Name: podName,
  658. Labels: map[string]string{"test": "liveness"},
  659. },
  660. Spec: v1.PodSpec{
  661. Containers: []v1.Container{
  662. {
  663. Name: containerName,
  664. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  665. Command: []string{"/bin/sh", "-c", "sleep 5", "/crash/missing"},
  666. },
  667. },
  668. },
  669. }
  670. podClient.CreateSync(pod)
  671. time.Sleep(2 * kubelet.MaxContainerBackOff) // it takes slightly more than 2*x to get to a back-off of x
  672. // wait for a delay == capped delay of MaxContainerBackOff
  673. ginkgo.By("getting restart delay when capped")
  674. var (
  675. delay1 time.Duration
  676. err error
  677. )
  678. for i := 0; i < 3; i++ {
  679. delay1, err = getRestartDelay(podClient, podName, containerName)
  680. if err != nil {
  681. framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
  682. }
  683. if delay1 < kubelet.MaxContainerBackOff {
  684. continue
  685. }
  686. }
  687. if (delay1 < kubelet.MaxContainerBackOff) || (delay1 > maxBackOffTolerance) {
  688. framework.Failf("expected %s back-off got=%s in delay1", kubelet.MaxContainerBackOff, delay1)
  689. }
  690. ginkgo.By("getting restart delay after a capped delay")
  691. delay2, err := getRestartDelay(podClient, podName, containerName)
  692. if err != nil {
  693. framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
  694. }
  695. if delay2 < kubelet.MaxContainerBackOff || delay2 > maxBackOffTolerance { // syncloop cumulative drift
  696. framework.Failf("expected %s back-off got=%s on delay2", kubelet.MaxContainerBackOff, delay2)
  697. }
  698. })
  699. // TODO(freehan): label the test to be [NodeConformance] after tests are proven to be stable.
  700. ginkgo.It("should support pod readiness gates [NodeFeature:PodReadinessGate]", func() {
  701. podName := "pod-ready"
  702. readinessGate1 := "k8s.io/test-condition1"
  703. readinessGate2 := "k8s.io/test-condition2"
  704. patchStatusFmt := `{"status":{"conditions":[{"type":%q, "status":%q}]}}`
  705. pod := &v1.Pod{
  706. ObjectMeta: metav1.ObjectMeta{
  707. Name: podName,
  708. Labels: map[string]string{"test": "pod-readiness-gate"},
  709. },
  710. Spec: v1.PodSpec{
  711. Containers: []v1.Container{
  712. {
  713. Name: "pod-readiness-gate",
  714. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  715. Command: []string{"/bin/sh", "-c", "echo container is alive; sleep 10000"},
  716. },
  717. },
  718. ReadinessGates: []v1.PodReadinessGate{
  719. {ConditionType: v1.PodConditionType(readinessGate1)},
  720. {ConditionType: v1.PodConditionType(readinessGate2)},
  721. },
  722. },
  723. }
  724. validatePodReadiness := func(expectReady bool) {
  725. err := wait.Poll(time.Second, maxReadyStatusUpdateTolerance, func() (bool, error) {
  726. podReady := podClient.PodIsReady(podName)
  727. res := expectReady == podReady
  728. if !res {
  729. e2elog.Logf("Expect the Ready condition of pod %q to be %v, but got %v", podName, expectReady, podReady)
  730. }
  731. return res, nil
  732. })
  733. framework.ExpectNoError(err)
  734. }
  735. ginkgo.By("submitting the pod to kubernetes")
  736. podClient.CreateSync(pod)
  737. gomega.Expect(podClient.PodIsReady(podName)).To(gomega.BeFalse(), "Expect pod's Ready condition to be false initially.")
  738. ginkgo.By(fmt.Sprintf("patching pod status with condition %q to true", readinessGate1))
  739. _, err := podClient.Patch(podName, types.StrategicMergePatchType, []byte(fmt.Sprintf(patchStatusFmt, readinessGate1, "True")), "status")
  740. framework.ExpectNoError(err)
  741. // Sleep for 10 seconds.
  742. time.Sleep(maxReadyStatusUpdateTolerance)
  743. gomega.Expect(podClient.PodIsReady(podName)).To(gomega.BeFalse(), "Expect pod's Ready condition to be false with only one condition in readinessGates equal to True")
  744. ginkgo.By(fmt.Sprintf("patching pod status with condition %q to true", readinessGate2))
  745. _, err = podClient.Patch(podName, types.StrategicMergePatchType, []byte(fmt.Sprintf(patchStatusFmt, readinessGate2, "True")), "status")
  746. framework.ExpectNoError(err)
  747. validatePodReadiness(true)
  748. ginkgo.By(fmt.Sprintf("patching pod status with condition %q to false", readinessGate1))
  749. _, err = podClient.Patch(podName, types.StrategicMergePatchType, []byte(fmt.Sprintf(patchStatusFmt, readinessGate1, "False")), "status")
  750. framework.ExpectNoError(err)
  751. validatePodReadiness(false)
  752. })
  753. })