pods.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 framework
  14. import (
  15. "context"
  16. "fmt"
  17. "regexp"
  18. "sync"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. apierrors "k8s.io/apimachinery/pkg/api/errors"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "k8s.io/apimachinery/pkg/util/sets"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. "k8s.io/client-go/kubernetes/scheme"
  27. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  28. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  29. "k8s.io/kubernetes/pkg/kubelet/events"
  30. "k8s.io/kubernetes/pkg/kubelet/sysctl"
  31. "github.com/onsi/ginkgo"
  32. "github.com/onsi/gomega"
  33. // TODO: Remove the following imports (ref: https://github.com/kubernetes/kubernetes/issues/81245)
  34. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  35. )
  36. // DefaultPodDeletionTimeout is the default timeout for deleting pod
  37. const DefaultPodDeletionTimeout = 3 * time.Minute
  38. // ImageWhiteList is the images used in the current test suite. It should be initialized in test suite and
  39. // the images in the white list should be pre-pulled in the test suite. Currently, this is only used by
  40. // node e2e test.
  41. var ImageWhiteList sets.String
  42. // PodClient is a convenience method for getting a pod client interface in the framework's namespace,
  43. // possibly applying test-suite specific transformations to the pod spec, e.g. for
  44. // node e2e pod scheduling.
  45. func (f *Framework) PodClient() *PodClient {
  46. return &PodClient{
  47. f: f,
  48. PodInterface: f.ClientSet.CoreV1().Pods(f.Namespace.Name),
  49. }
  50. }
  51. // PodClientNS is a convenience method for getting a pod client interface in an alternative namespace,
  52. // possibly applying test-suite specific transformations to the pod spec, e.g. for
  53. // node e2e pod scheduling.
  54. func (f *Framework) PodClientNS(namespace string) *PodClient {
  55. return &PodClient{
  56. f: f,
  57. PodInterface: f.ClientSet.CoreV1().Pods(namespace),
  58. }
  59. }
  60. // PodClient is a struct for pod client.
  61. type PodClient struct {
  62. f *Framework
  63. v1core.PodInterface
  64. }
  65. // Create creates a new pod according to the framework specifications (don't wait for it to start).
  66. func (c *PodClient) Create(pod *v1.Pod) *v1.Pod {
  67. c.mungeSpec(pod)
  68. p, err := c.PodInterface.Create(context.TODO(), pod, metav1.CreateOptions{})
  69. ExpectNoError(err, "Error creating Pod")
  70. return p
  71. }
  72. // CreateSync creates a new pod according to the framework specifications, and wait for it to start.
  73. func (c *PodClient) CreateSync(pod *v1.Pod) *v1.Pod {
  74. namespace := c.f.Namespace.Name
  75. p := c.Create(pod)
  76. ExpectNoError(e2epod.WaitForPodNameRunningInNamespace(c.f.ClientSet, p.Name, namespace))
  77. // Get the newest pod after it becomes running, some status may change after pod created, such as pod ip.
  78. p, err := c.Get(context.TODO(), p.Name, metav1.GetOptions{})
  79. ExpectNoError(err)
  80. return p
  81. }
  82. // CreateBatch create a batch of pods. All pods are created before waiting.
  83. func (c *PodClient) CreateBatch(pods []*v1.Pod) []*v1.Pod {
  84. ps := make([]*v1.Pod, len(pods))
  85. var wg sync.WaitGroup
  86. for i, pod := range pods {
  87. wg.Add(1)
  88. go func(i int, pod *v1.Pod) {
  89. defer wg.Done()
  90. defer ginkgo.GinkgoRecover()
  91. ps[i] = c.CreateSync(pod)
  92. }(i, pod)
  93. }
  94. wg.Wait()
  95. return ps
  96. }
  97. // Update updates the pod object. It retries if there is a conflict, throw out error if
  98. // there is any other apierrors. name is the pod name, updateFn is the function updating the
  99. // pod object.
  100. func (c *PodClient) Update(name string, updateFn func(pod *v1.Pod)) {
  101. ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*30, func() (bool, error) {
  102. pod, err := c.PodInterface.Get(context.TODO(), name, metav1.GetOptions{})
  103. if err != nil {
  104. return false, fmt.Errorf("failed to get pod %q: %v", name, err)
  105. }
  106. updateFn(pod)
  107. _, err = c.PodInterface.Update(context.TODO(), pod, metav1.UpdateOptions{})
  108. if err == nil {
  109. Logf("Successfully updated pod %q", name)
  110. return true, nil
  111. }
  112. if apierrors.IsConflict(err) {
  113. Logf("Conflicting update to pod %q, re-get and re-update: %v", name, err)
  114. return false, nil
  115. }
  116. return false, fmt.Errorf("failed to update pod %q: %v", name, err)
  117. }))
  118. }
  119. // DeleteSync deletes the pod and wait for the pod to disappear for `timeout`. If the pod doesn't
  120. // disappear before the timeout, it will fail the test.
  121. func (c *PodClient) DeleteSync(name string, options *metav1.DeleteOptions, timeout time.Duration) {
  122. namespace := c.f.Namespace.Name
  123. err := c.Delete(context.TODO(), name, options)
  124. if err != nil && !apierrors.IsNotFound(err) {
  125. Failf("Failed to delete pod %q: %v", name, err)
  126. }
  127. gomega.Expect(e2epod.WaitForPodToDisappear(c.f.ClientSet, namespace, name, labels.Everything(),
  128. 2*time.Second, timeout)).To(gomega.Succeed(), "wait for pod %q to disappear", name)
  129. }
  130. // mungeSpec apply test-suite specific transformations to the pod spec.
  131. func (c *PodClient) mungeSpec(pod *v1.Pod) {
  132. if !TestContext.NodeE2E {
  133. return
  134. }
  135. gomega.Expect(pod.Spec.NodeName).To(gomega.Or(gomega.BeZero(), gomega.Equal(TestContext.NodeName)), "Test misconfigured")
  136. pod.Spec.NodeName = TestContext.NodeName
  137. // Node e2e does not support the default DNSClusterFirst policy. Set
  138. // the policy to DNSDefault, which is configured per node.
  139. pod.Spec.DNSPolicy = v1.DNSDefault
  140. // PrepullImages only works for node e2e now. For cluster e2e, image prepull is not enforced,
  141. // we should not munge ImagePullPolicy for cluster e2e pods.
  142. if !TestContext.PrepullImages {
  143. return
  144. }
  145. // If prepull is enabled, munge the container spec to make sure the images are not pulled
  146. // during the test.
  147. for i := range pod.Spec.Containers {
  148. c := &pod.Spec.Containers[i]
  149. if c.ImagePullPolicy == v1.PullAlways {
  150. // If the image pull policy is PullAlways, the image doesn't need to be in
  151. // the white list or pre-pulled, because the image is expected to be pulled
  152. // in the test anyway.
  153. continue
  154. }
  155. // If the image policy is not PullAlways, the image must be in the white list and
  156. // pre-pulled.
  157. gomega.Expect(ImageWhiteList.Has(c.Image)).To(gomega.BeTrue(), "Image %q is not in the white list, consider adding it to CommonImageWhiteList in test/e2e/common/util.go or NodeImageWhiteList in test/e2e_node/image_list.go", c.Image)
  158. // Do not pull images during the tests because the images in white list should have
  159. // been prepulled.
  160. c.ImagePullPolicy = v1.PullNever
  161. }
  162. }
  163. // WaitForSuccess waits for pod to succeed.
  164. // TODO(random-liu): Move pod wait function into this file
  165. func (c *PodClient) WaitForSuccess(name string, timeout time.Duration) {
  166. f := c.f
  167. gomega.Expect(e2epod.WaitForPodCondition(f.ClientSet, f.Namespace.Name, name, fmt.Sprintf("%s or %s", v1.PodSucceeded, v1.PodFailed), timeout,
  168. func(pod *v1.Pod) (bool, error) {
  169. switch pod.Status.Phase {
  170. case v1.PodFailed:
  171. return true, fmt.Errorf("pod %q failed with reason: %q, message: %q", name, pod.Status.Reason, pod.Status.Message)
  172. case v1.PodSucceeded:
  173. return true, nil
  174. default:
  175. return false, nil
  176. }
  177. },
  178. )).To(gomega.Succeed(), "wait for pod %q to success", name)
  179. }
  180. // WaitForFinish waits for pod to finish running, regardless of success or failure.
  181. func (c *PodClient) WaitForFinish(name string, timeout time.Duration) {
  182. f := c.f
  183. gomega.Expect(e2epod.WaitForPodCondition(f.ClientSet, f.Namespace.Name, name, fmt.Sprintf("%s or %s", v1.PodSucceeded, v1.PodFailed), timeout,
  184. func(pod *v1.Pod) (bool, error) {
  185. switch pod.Status.Phase {
  186. case v1.PodFailed:
  187. return true, nil
  188. case v1.PodSucceeded:
  189. return true, nil
  190. default:
  191. return false, nil
  192. }
  193. },
  194. )).To(gomega.Succeed(), "wait for pod %q to finish running", name)
  195. }
  196. // WaitForErrorEventOrSuccess waits for pod to succeed or an error event for that pod.
  197. func (c *PodClient) WaitForErrorEventOrSuccess(pod *v1.Pod) (*v1.Event, error) {
  198. var ev *v1.Event
  199. err := wait.Poll(Poll, PodStartTimeout, func() (bool, error) {
  200. evnts, err := c.f.ClientSet.CoreV1().Events(pod.Namespace).Search(scheme.Scheme, pod)
  201. if err != nil {
  202. return false, fmt.Errorf("error in listing events: %s", err)
  203. }
  204. for _, e := range evnts.Items {
  205. switch e.Reason {
  206. case events.KillingContainer, events.FailedToCreateContainer, sysctl.ForbiddenReason:
  207. ev = &e
  208. return true, nil
  209. case events.StartedContainer:
  210. return true, nil
  211. default:
  212. // ignore all other errors
  213. }
  214. }
  215. return false, nil
  216. })
  217. return ev, err
  218. }
  219. // MatchContainerOutput gets output of a container and match expected regexp in the output.
  220. func (c *PodClient) MatchContainerOutput(name string, containerName string, expectedRegexp string) error {
  221. f := c.f
  222. output, err := e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, name, containerName)
  223. if err != nil {
  224. return fmt.Errorf("failed to get output for container %q of pod %q", containerName, name)
  225. }
  226. regex, err := regexp.Compile(expectedRegexp)
  227. if err != nil {
  228. return fmt.Errorf("failed to compile regexp %q: %v", expectedRegexp, err)
  229. }
  230. if !regex.MatchString(output) {
  231. return fmt.Errorf("failed to match regexp %q in output %q", expectedRegexp, output)
  232. }
  233. return nil
  234. }
  235. // PodIsReady returns true if the specified pod is ready. Otherwise false.
  236. func (c *PodClient) PodIsReady(name string) bool {
  237. pod, err := c.Get(context.TODO(), name, metav1.GetOptions{})
  238. ExpectNoError(err)
  239. return podutil.IsPodReady(pod)
  240. }