pods.go 29 KB

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