e2e.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. Copyright 2015 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 e2e
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "path"
  19. "testing"
  20. "time"
  21. "k8s.io/klog"
  22. "github.com/onsi/ginkgo"
  23. "github.com/onsi/ginkgo/config"
  24. "github.com/onsi/ginkgo/reporters"
  25. "github.com/onsi/gomega"
  26. v1 "k8s.io/api/core/v1"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. runtimeutils "k8s.io/apimachinery/pkg/util/runtime"
  29. "k8s.io/apimachinery/pkg/util/wait"
  30. "k8s.io/component-base/logs"
  31. "k8s.io/component-base/version"
  32. commontest "k8s.io/kubernetes/test/e2e/common"
  33. "k8s.io/kubernetes/test/e2e/framework"
  34. e2ekubectl "k8s.io/kubernetes/test/e2e/framework/kubectl"
  35. e2enode "k8s.io/kubernetes/test/e2e/framework/node"
  36. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  37. "k8s.io/kubernetes/test/e2e/manifest"
  38. e2ereporters "k8s.io/kubernetes/test/e2e/reporters"
  39. testutils "k8s.io/kubernetes/test/utils"
  40. utilnet "k8s.io/utils/net"
  41. clientset "k8s.io/client-go/kubernetes"
  42. // ensure auth plugins are loaded
  43. _ "k8s.io/client-go/plugin/pkg/client/auth"
  44. // ensure that cloud providers are loaded
  45. _ "k8s.io/kubernetes/test/e2e/framework/providers/aws"
  46. _ "k8s.io/kubernetes/test/e2e/framework/providers/azure"
  47. _ "k8s.io/kubernetes/test/e2e/framework/providers/gce"
  48. _ "k8s.io/kubernetes/test/e2e/framework/providers/kubemark"
  49. _ "k8s.io/kubernetes/test/e2e/framework/providers/openstack"
  50. _ "k8s.io/kubernetes/test/e2e/framework/providers/vsphere"
  51. )
  52. var _ = ginkgo.SynchronizedBeforeSuite(func() []byte {
  53. // Reference common test to make the import valid.
  54. commontest.CurrentSuite = commontest.E2E
  55. setupSuite()
  56. return nil
  57. }, func(data []byte) {
  58. // Run on all Ginkgo nodes
  59. setupSuitePerGinkgoNode()
  60. })
  61. var _ = ginkgo.SynchronizedAfterSuite(func() {
  62. CleanupSuite()
  63. }, func() {
  64. AfterSuiteActions()
  65. })
  66. // RunE2ETests checks configuration parameters (specified through flags) and then runs
  67. // E2E tests using the Ginkgo runner.
  68. // If a "report directory" is specified, one or more JUnit test reports will be
  69. // generated in this directory, and cluster logs will also be saved.
  70. // This function is called on each Ginkgo node in parallel mode.
  71. func RunE2ETests(t *testing.T) {
  72. runtimeutils.ReallyCrash = true
  73. logs.InitLogs()
  74. defer logs.FlushLogs()
  75. gomega.RegisterFailHandler(framework.Fail)
  76. // Disable skipped tests unless they are explicitly requested.
  77. if config.GinkgoConfig.FocusString == "" && config.GinkgoConfig.SkipString == "" {
  78. config.GinkgoConfig.SkipString = `\[Flaky\]|\[Feature:.+\]`
  79. }
  80. // Run tests through the Ginkgo runner with output to console + JUnit for Jenkins
  81. var r []ginkgo.Reporter
  82. if framework.TestContext.ReportDir != "" {
  83. // TODO: we should probably only be trying to create this directory once
  84. // rather than once-per-Ginkgo-node.
  85. if err := os.MkdirAll(framework.TestContext.ReportDir, 0755); err != nil {
  86. klog.Errorf("Failed creating report directory: %v", err)
  87. } else {
  88. r = append(r, reporters.NewJUnitReporter(path.Join(framework.TestContext.ReportDir, fmt.Sprintf("junit_%v%02d.xml", framework.TestContext.ReportPrefix, config.GinkgoConfig.ParallelNode))))
  89. }
  90. }
  91. // Stream the progress to stdout and optionally a URL accepting progress updates.
  92. r = append(r, e2ereporters.NewProgressReporter(framework.TestContext.ProgressReportURL))
  93. klog.Infof("Starting e2e run %q on Ginkgo node %d", framework.RunID, config.GinkgoConfig.ParallelNode)
  94. ginkgo.RunSpecsWithDefaultAndCustomReporters(t, "Kubernetes e2e suite", r)
  95. }
  96. // Run a test container to try and contact the Kubernetes api-server from a pod, wait for it
  97. // to flip to Ready, log its output and delete it.
  98. func runKubernetesServiceTestContainer(c clientset.Interface, ns string) {
  99. path := "test/images/clusterapi-tester/pod.yaml"
  100. framework.Logf("Parsing pod from %v", path)
  101. p, err := manifest.PodFromManifest(path)
  102. if err != nil {
  103. framework.Logf("Failed to parse clusterapi-tester from manifest %v: %v", path, err)
  104. return
  105. }
  106. p.Namespace = ns
  107. if _, err := c.CoreV1().Pods(ns).Create(context.TODO(), p, metav1.CreateOptions{}); err != nil {
  108. framework.Logf("Failed to create %v: %v", p.Name, err)
  109. return
  110. }
  111. defer func() {
  112. if err := c.CoreV1().Pods(ns).Delete(context.TODO(), p.Name, nil); err != nil {
  113. framework.Logf("Failed to delete pod %v: %v", p.Name, err)
  114. }
  115. }()
  116. timeout := 5 * time.Minute
  117. if err := e2epod.WaitForPodCondition(c, ns, p.Name, "clusterapi-tester", timeout, testutils.PodRunningReady); err != nil {
  118. framework.Logf("Pod %v took longer than %v to enter running/ready: %v", p.Name, timeout, err)
  119. return
  120. }
  121. logs, err := e2epod.GetPodLogs(c, ns, p.Name, p.Spec.Containers[0].Name)
  122. if err != nil {
  123. framework.Logf("Failed to retrieve logs from %v: %v", p.Name, err)
  124. } else {
  125. framework.Logf("Output of clusterapi-tester:\n%v", logs)
  126. }
  127. }
  128. // getDefaultClusterIPFamily obtains the default IP family of the cluster
  129. // using the Cluster IP address of the kubernetes service created in the default namespace
  130. // This unequivocally identifies the default IP family because services are single family
  131. // TODO: dual-stack may support multiple families per service
  132. // but we can detect if a cluster is dual stack because pods have two addresses (one per family)
  133. func getDefaultClusterIPFamily(c clientset.Interface) string {
  134. // Get the ClusterIP of the kubernetes service created in the default namespace
  135. svc, err := c.CoreV1().Services(metav1.NamespaceDefault).Get(context.TODO(), "kubernetes", metav1.GetOptions{})
  136. if err != nil {
  137. framework.Failf("Failed to get kubernetes service ClusterIP: %v", err)
  138. }
  139. if utilnet.IsIPv6String(svc.Spec.ClusterIP) {
  140. return "ipv6"
  141. }
  142. return "ipv4"
  143. }
  144. // waitForDaemonSets for all daemonsets in the given namespace to be ready
  145. // (defined as all but 'allowedNotReadyNodes' pods associated with that
  146. // daemonset are ready).
  147. func waitForDaemonSets(c clientset.Interface, ns string, allowedNotReadyNodes int32, timeout time.Duration) error {
  148. start := time.Now()
  149. framework.Logf("Waiting up to %v for all daemonsets in namespace '%s' to start",
  150. timeout, ns)
  151. return wait.PollImmediate(framework.Poll, timeout, func() (bool, error) {
  152. dsList, err := c.AppsV1().DaemonSets(ns).List(context.TODO(), metav1.ListOptions{})
  153. if err != nil {
  154. framework.Logf("Error getting daemonsets in namespace: '%s': %v", ns, err)
  155. if testutils.IsRetryableAPIError(err) {
  156. return false, nil
  157. }
  158. return false, err
  159. }
  160. var notReadyDaemonSets []string
  161. for _, ds := range dsList.Items {
  162. framework.Logf("%d / %d pods ready in namespace '%s' in daemonset '%s' (%d seconds elapsed)", ds.Status.NumberReady, ds.Status.DesiredNumberScheduled, ns, ds.ObjectMeta.Name, int(time.Since(start).Seconds()))
  163. if ds.Status.DesiredNumberScheduled-ds.Status.NumberReady > allowedNotReadyNodes {
  164. notReadyDaemonSets = append(notReadyDaemonSets, ds.ObjectMeta.Name)
  165. }
  166. }
  167. if len(notReadyDaemonSets) > 0 {
  168. framework.Logf("there are not ready daemonsets: %v", notReadyDaemonSets)
  169. return false, nil
  170. }
  171. return true, nil
  172. })
  173. }
  174. // setupSuite is the boilerplate that can be used to setup ginkgo test suites, on the SynchronizedBeforeSuite step.
  175. // There are certain operations we only want to run once per overall test invocation
  176. // (such as deleting old namespaces, or verifying that all system pods are running.
  177. // Because of the way Ginkgo runs tests in parallel, we must use SynchronizedBeforeSuite
  178. // to ensure that these operations only run on the first parallel Ginkgo node.
  179. //
  180. // This function takes two parameters: one function which runs on only the first Ginkgo node,
  181. // returning an opaque byte array, and then a second function which runs on all Ginkgo nodes,
  182. // accepting the byte array.
  183. func setupSuite() {
  184. // Run only on Ginkgo node 1
  185. switch framework.TestContext.Provider {
  186. case "gce", "gke":
  187. framework.LogClusterImageSources()
  188. }
  189. c, err := framework.LoadClientset()
  190. if err != nil {
  191. klog.Fatal("Error loading client: ", err)
  192. }
  193. // Delete any namespaces except those created by the system. This ensures no
  194. // lingering resources are left over from a previous test run.
  195. if framework.TestContext.CleanStart {
  196. deleted, err := framework.DeleteNamespaces(c, nil, /* deleteFilter */
  197. []string{
  198. metav1.NamespaceSystem,
  199. metav1.NamespaceDefault,
  200. metav1.NamespacePublic,
  201. v1.NamespaceNodeLease,
  202. })
  203. if err != nil {
  204. framework.Failf("Error deleting orphaned namespaces: %v", err)
  205. }
  206. klog.Infof("Waiting for deletion of the following namespaces: %v", deleted)
  207. if err := framework.WaitForNamespacesDeleted(c, deleted, framework.NamespaceCleanupTimeout); err != nil {
  208. framework.Failf("Failed to delete orphaned namespaces %v: %v", deleted, err)
  209. }
  210. }
  211. // In large clusters we may get to this point but still have a bunch
  212. // of nodes without Routes created. Since this would make a node
  213. // unschedulable, we need to wait until all of them are schedulable.
  214. framework.ExpectNoError(framework.WaitForAllNodesSchedulable(c, framework.TestContext.NodeSchedulableTimeout))
  215. // If NumNodes is not specified then auto-detect how many are scheduleable and not tainted
  216. if framework.TestContext.CloudConfig.NumNodes == framework.DefaultNumNodes {
  217. nodes, err := e2enode.GetReadySchedulableNodes(c)
  218. framework.ExpectNoError(err)
  219. framework.TestContext.CloudConfig.NumNodes = len(nodes.Items)
  220. }
  221. // Ensure all pods are running and ready before starting tests (otherwise,
  222. // cluster infrastructure pods that are being pulled or started can block
  223. // test pods from running, and tests that ensure all pods are running and
  224. // ready will fail).
  225. podStartupTimeout := framework.TestContext.SystemPodsStartupTimeout
  226. // TODO: In large clusters, we often observe a non-starting pods due to
  227. // #41007. To avoid those pods preventing the whole test runs (and just
  228. // wasting the whole run), we allow for some not-ready pods (with the
  229. // number equal to the number of allowed not-ready nodes).
  230. if err := e2epod.WaitForPodsRunningReady(c, metav1.NamespaceSystem, int32(framework.TestContext.MinStartupPods), int32(framework.TestContext.AllowedNotReadyNodes), podStartupTimeout, map[string]string{}); err != nil {
  231. framework.DumpAllNamespaceInfo(c, metav1.NamespaceSystem)
  232. e2ekubectl.LogFailedContainers(c, metav1.NamespaceSystem, framework.Logf)
  233. runKubernetesServiceTestContainer(c, metav1.NamespaceDefault)
  234. framework.Failf("Error waiting for all pods to be running and ready: %v", err)
  235. }
  236. if err := waitForDaemonSets(c, metav1.NamespaceSystem, int32(framework.TestContext.AllowedNotReadyNodes), framework.TestContext.SystemDaemonsetStartupTimeout); err != nil {
  237. framework.Logf("WARNING: Waiting for all daemonsets to be ready failed: %v", err)
  238. }
  239. // Log the version of the server and this client.
  240. framework.Logf("e2e test version: %s", version.Get().GitVersion)
  241. dc := c.DiscoveryClient
  242. serverVersion, serverErr := dc.ServerVersion()
  243. if serverErr != nil {
  244. framework.Logf("Unexpected server error retrieving version: %v", serverErr)
  245. }
  246. if serverVersion != nil {
  247. framework.Logf("kube-apiserver version: %s", serverVersion.GitVersion)
  248. }
  249. if framework.TestContext.NodeKiller.Enabled {
  250. nodeKiller := framework.NewNodeKiller(framework.TestContext.NodeKiller, c, framework.TestContext.Provider)
  251. go nodeKiller.Run(framework.TestContext.NodeKiller.NodeKillerStopCh)
  252. }
  253. }
  254. // setupSuitePerGinkgoNode is the boilerplate that can be used to setup ginkgo test suites, on the SynchronizedBeforeSuite step.
  255. // There are certain operations we only want to run once per overall test invocation on each Ginkgo node
  256. // such as making some global variables accessible to all parallel executions
  257. // Because of the way Ginkgo runs tests in parallel, we must use SynchronizedBeforeSuite
  258. // Ref: https://onsi.github.io/ginkgo/#parallel-specs
  259. func setupSuitePerGinkgoNode() {
  260. // Obtain the default IP family of the cluster
  261. // Some e2e test are designed to work on IPv4 only, this global variable
  262. // allows to adapt those tests to work on both IPv4 and IPv6
  263. // TODO: dual-stack
  264. // the dual stack clusters can be ipv4-ipv6 or ipv6-ipv4, order matters,
  265. // and services use the primary IP family by default
  266. c, err := framework.LoadClientset()
  267. if err != nil {
  268. klog.Fatal("Error loading client: ", err)
  269. }
  270. framework.TestContext.IPFamily = getDefaultClusterIPFamily(c)
  271. framework.Logf("Cluster IP family: %s", framework.TestContext.IPFamily)
  272. }