example_cluster_dns.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 network
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "time"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. clientset "k8s.io/client-go/kubernetes"
  25. api "k8s.io/kubernetes/pkg/apis/core"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  28. "github.com/onsi/ginkgo"
  29. )
  30. const (
  31. dnsReadyTimeout = time.Minute
  32. )
  33. const queryDNSPythonTemplate string = `
  34. import socket
  35. try:
  36. socket.gethostbyname('%s')
  37. print('ok')
  38. except:
  39. print('err')`
  40. var _ = SIGDescribe("ClusterDns [Feature:Example]", func() {
  41. f := framework.NewDefaultFramework("cluster-dns")
  42. var c clientset.Interface
  43. ginkgo.BeforeEach(func() {
  44. c = f.ClientSet
  45. })
  46. ginkgo.It("should create pod that uses dns", func() {
  47. mkpath := func(file string) string {
  48. return filepath.Join(os.Getenv("GOPATH"), "src/k8s.io/examples/staging/cluster-dns", file)
  49. }
  50. // contrary to the example, this test does not use contexts, for simplicity
  51. // namespaces are passed directly.
  52. // Also, for simplicity, we don't use yamls with namespaces, but we
  53. // create testing namespaces instead.
  54. backendRcYaml := mkpath("dns-backend-rc.yaml")
  55. backendRcName := "dns-backend"
  56. backendSvcYaml := mkpath("dns-backend-service.yaml")
  57. backendSvcName := "dns-backend"
  58. backendPodName := "dns-backend"
  59. frontendPodYaml := mkpath("dns-frontend-pod.yaml")
  60. frontendPodName := "dns-frontend"
  61. frontendPodContainerName := "dns-frontend"
  62. podOutput := "Hello World!"
  63. // we need two namespaces anyway, so let's forget about
  64. // the one created in BeforeEach and create two new ones.
  65. namespaces := []*v1.Namespace{nil, nil}
  66. for i := range namespaces {
  67. var err error
  68. namespaceName := fmt.Sprintf("dnsexample%d", i)
  69. namespaces[i], err = f.CreateNamespace(namespaceName, nil)
  70. framework.ExpectNoError(err, "failed to create namespace: %s", namespaceName)
  71. }
  72. for _, ns := range namespaces {
  73. framework.RunKubectlOrDie("create", "-f", backendRcYaml, getNsCmdFlag(ns))
  74. }
  75. for _, ns := range namespaces {
  76. framework.RunKubectlOrDie("create", "-f", backendSvcYaml, getNsCmdFlag(ns))
  77. }
  78. // wait for objects
  79. for _, ns := range namespaces {
  80. framework.WaitForControlledPodsRunning(c, ns.Name, backendRcName, api.Kind("ReplicationController"))
  81. framework.WaitForService(c, ns.Name, backendSvcName, true, framework.Poll, framework.ServiceStartTimeout)
  82. }
  83. // it is not enough that pods are running because they may be set to running, but
  84. // the application itself may have not been initialized. Just query the application.
  85. for _, ns := range namespaces {
  86. label := labels.SelectorFromSet(labels.Set(map[string]string{"name": backendRcName}))
  87. options := metav1.ListOptions{LabelSelector: label.String()}
  88. pods, err := c.CoreV1().Pods(ns.Name).List(options)
  89. framework.ExpectNoError(err, "failed to list pods in namespace: %s", ns.Name)
  90. err = framework.PodsResponding(c, ns.Name, backendPodName, false, pods)
  91. framework.ExpectNoError(err, "waiting for all pods to respond")
  92. e2elog.Logf("found %d backend pods responding in namespace %s", len(pods.Items), ns.Name)
  93. err = framework.ServiceResponding(c, ns.Name, backendSvcName)
  94. framework.ExpectNoError(err, "waiting for the service to respond")
  95. }
  96. // Now another tricky part:
  97. // It may happen that the service name is not yet in DNS.
  98. // So if we start our pod, it will fail. We must make sure
  99. // the name is already resolvable. So let's try to query DNS from
  100. // the pod we have, until we find our service name.
  101. // This complicated code may be removed if the pod itself retried after
  102. // dns error or timeout.
  103. // This code is probably unnecessary, but let's stay on the safe side.
  104. label := labels.SelectorFromSet(labels.Set(map[string]string{"name": backendPodName}))
  105. options := metav1.ListOptions{LabelSelector: label.String()}
  106. pods, err := c.CoreV1().Pods(namespaces[0].Name).List(options)
  107. if err != nil || pods == nil || len(pods.Items) == 0 {
  108. framework.Failf("no running pods found")
  109. }
  110. podName := pods.Items[0].Name
  111. queryDNS := fmt.Sprintf(queryDNSPythonTemplate, backendSvcName+"."+namespaces[0].Name)
  112. _, err = framework.LookForStringInPodExec(namespaces[0].Name, podName, []string{"python", "-c", queryDNS}, "ok", dnsReadyTimeout)
  113. framework.ExpectNoError(err, "waiting for output from pod exec")
  114. updatedPodYaml := prepareResourceWithReplacedString(frontendPodYaml, fmt.Sprintf("dns-backend.development.svc.%s", framework.TestContext.ClusterDNSDomain), fmt.Sprintf("dns-backend.%s.svc.%s", namespaces[0].Name, framework.TestContext.ClusterDNSDomain))
  115. // create a pod in each namespace
  116. for _, ns := range namespaces {
  117. framework.NewKubectlCommand("create", "-f", "-", getNsCmdFlag(ns)).WithStdinData(updatedPodYaml).ExecOrDie()
  118. }
  119. // wait until the pods have been scheduler, i.e. are not Pending anymore. Remember
  120. // that we cannot wait for the pods to be running because our pods terminate by themselves.
  121. for _, ns := range namespaces {
  122. err := framework.WaitForPodNotPending(c, ns.Name, frontendPodName)
  123. framework.ExpectNoError(err)
  124. }
  125. // wait for pods to print their result
  126. for _, ns := range namespaces {
  127. _, err := framework.LookForStringInLog(ns.Name, frontendPodName, frontendPodContainerName, podOutput, framework.PodStartTimeout)
  128. framework.ExpectNoError(err, "pod %s failed to print result in logs", frontendPodName)
  129. }
  130. })
  131. })
  132. func getNsCmdFlag(ns *v1.Namespace) string {
  133. return fmt.Sprintf("--namespace=%v", ns.Name)
  134. }
  135. // pass enough context with the 'old' parameter so that it replaces what your really intended.
  136. func prepareResourceWithReplacedString(inputFile, old, new string) string {
  137. f, err := os.Open(inputFile)
  138. framework.ExpectNoError(err, "failed to open file: %s", inputFile)
  139. defer f.Close()
  140. data, err := ioutil.ReadAll(f)
  141. framework.ExpectNoError(err, "failed to read from file: %s", inputFile)
  142. podYaml := strings.Replace(string(data), old, new, 1)
  143. return podYaml
  144. }