PageRenderTime 88ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/test/e2e/kubectl/kubectl.go

https://bitbucket.org/Jake-Qu/kubernetes-mirror
Go | 2140 lines | 1688 code | 249 blank | 203 comment | 348 complexity | 3525a356556ba49e8633851280fa87cf MD5 | raw file
Possible License(s): MIT, MPL-2.0-no-copyleft-exception, 0BSD, CC0-1.0, BSD-2-Clause, Apache-2.0, BSD-3-Clause
  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. // OWNER = sig/cli
  14. package kubectl
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "log"
  23. "mime/multipart"
  24. "net"
  25. "net/http"
  26. "net/http/httptest"
  27. "os"
  28. "os/exec"
  29. "path"
  30. "path/filepath"
  31. "regexp"
  32. "sort"
  33. "strconv"
  34. "strings"
  35. "text/template"
  36. "time"
  37. "github.com/elazarl/goproxy"
  38. "github.com/ghodss/yaml"
  39. "k8s.io/api/core/v1"
  40. rbacv1beta1 "k8s.io/api/rbac/v1beta1"
  41. apierrs "k8s.io/apimachinery/pkg/api/errors"
  42. "k8s.io/apimachinery/pkg/api/resource"
  43. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  44. "k8s.io/apimachinery/pkg/labels"
  45. "k8s.io/apimachinery/pkg/runtime/schema"
  46. utilnet "k8s.io/apimachinery/pkg/util/net"
  47. "k8s.io/apimachinery/pkg/util/uuid"
  48. "k8s.io/apimachinery/pkg/util/wait"
  49. "k8s.io/apiserver/pkg/authentication/serviceaccount"
  50. genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
  51. clientset "k8s.io/client-go/kubernetes"
  52. "k8s.io/kubernetes/pkg/controller"
  53. "k8s.io/kubernetes/test/e2e/framework"
  54. "k8s.io/kubernetes/test/e2e/generated"
  55. "k8s.io/kubernetes/test/e2e/scheduling"
  56. testutils "k8s.io/kubernetes/test/utils"
  57. uexec "k8s.io/utils/exec"
  58. . "github.com/onsi/ginkgo"
  59. . "github.com/onsi/gomega"
  60. "k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
  61. imageutils "k8s.io/kubernetes/test/utils/image"
  62. )
  63. const (
  64. updateDemoSelector = "name=update-demo"
  65. guestbookStartupTimeout = 10 * time.Minute
  66. guestbookResponseTimeout = 3 * time.Minute
  67. simplePodSelector = "name=nginx"
  68. simplePodName = "nginx"
  69. nginxDefaultOutput = "Welcome to nginx!"
  70. simplePodPort = 80
  71. pausePodSelector = "name=pause"
  72. pausePodName = "pause"
  73. runJobTimeout = 5 * time.Minute
  74. kubeCtlManifestPath = "test/e2e/testing-manifests/kubectl"
  75. redisControllerFilename = "redis-master-controller.json.in"
  76. redisServiceFilename = "redis-master-service.json"
  77. nginxDeployment1Filename = "nginx-deployment1.yaml.in"
  78. nginxDeployment2Filename = "nginx-deployment2.yaml.in"
  79. nginxDeployment3Filename = "nginx-deployment3.yaml.in"
  80. )
  81. var (
  82. nautilusImage = imageutils.GetE2EImage(imageutils.Nautilus)
  83. kittenImage = imageutils.GetE2EImage(imageutils.Kitten)
  84. redisImage = imageutils.GetE2EImage(imageutils.Redis)
  85. nginxImage = imageutils.GetE2EImage(imageutils.NginxSlim)
  86. busyboxImage = "busybox"
  87. )
  88. var testImages = struct {
  89. GBFrontendImage string
  90. PauseImage string
  91. NginxSlimImage string
  92. NginxSlimNewImage string
  93. RedisImage string
  94. GBRedisSlaveImage string
  95. NautilusImage string
  96. KittenImage string
  97. }{
  98. imageutils.GetE2EImage(imageutils.GBFrontend),
  99. imageutils.GetE2EImage(imageutils.Pause),
  100. imageutils.GetE2EImage(imageutils.NginxSlim),
  101. imageutils.GetE2EImage(imageutils.NginxSlimNew),
  102. imageutils.GetE2EImage(imageutils.Redis),
  103. imageutils.GetE2EImage(imageutils.GBRedisSlave),
  104. imageutils.GetE2EImage(imageutils.Nautilus),
  105. imageutils.GetE2EImage(imageutils.Kitten),
  106. }
  107. var (
  108. proxyRegexp = regexp.MustCompile("Starting to serve on 127.0.0.1:([0-9]+)")
  109. CronJobGroupVersionResourceAlpha = schema.GroupVersionResource{Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}
  110. CronJobGroupVersionResourceBeta = schema.GroupVersionResource{Group: "batch", Version: "v1beta1", Resource: "cronjobs"}
  111. )
  112. // Stops everything from filePath from namespace ns and checks if everything matching selectors from the given namespace is correctly stopped.
  113. // Aware of the kubectl example files map.
  114. func cleanupKubectlInputs(fileContents string, ns string, selectors ...string) {
  115. By("using delete to clean up resources")
  116. var nsArg string
  117. if ns != "" {
  118. nsArg = fmt.Sprintf("--namespace=%s", ns)
  119. }
  120. // support backward compatibility : file paths or raw json - since we are removing file path
  121. // dependencies from this test.
  122. framework.RunKubectlOrDieInput(fileContents, "delete", "--grace-period=0", "--force", "-f", "-", nsArg)
  123. framework.AssertCleanup(ns, selectors...)
  124. }
  125. func substituteImageName(content string) string {
  126. contentWithImageName := new(bytes.Buffer)
  127. tmpl, err := template.New("imagemanifest").Parse(content)
  128. if err != nil {
  129. framework.Failf("Failed Parse the template:", err)
  130. }
  131. err = tmpl.Execute(contentWithImageName, testImages)
  132. if err != nil {
  133. framework.Failf("Failed executing template:", err)
  134. }
  135. return contentWithImageName.String()
  136. }
  137. func readTestFileOrDie(file string) []byte {
  138. return generated.ReadOrDie(path.Join(kubeCtlManifestPath, file))
  139. }
  140. func runKubectlRetryOrDie(args ...string) string {
  141. var err error
  142. var output string
  143. for i := 0; i < 5; i++ {
  144. output, err = framework.RunKubectl(args...)
  145. if err == nil || (!strings.Contains(err.Error(), genericregistry.OptimisticLockErrorMsg) && !strings.Contains(err.Error(), "Operation cannot be fulfilled")) {
  146. break
  147. }
  148. time.Sleep(time.Second)
  149. }
  150. // Expect no errors to be present after retries are finished
  151. // Copied from framework #ExecOrDie
  152. framework.Logf("stdout: %q", output)
  153. Expect(err).NotTo(HaveOccurred())
  154. return output
  155. }
  156. // duplicated setup to avoid polluting "normal" clients with alpha features which confuses the generated clients
  157. var _ = SIGDescribe("Kubectl alpha client", func() {
  158. defer GinkgoRecover()
  159. f := framework.NewDefaultFramework("kubectl")
  160. var c clientset.Interface
  161. var ns string
  162. BeforeEach(func() {
  163. c = f.ClientSet
  164. ns = f.Namespace.Name
  165. })
  166. // Customized Wait / ForEach wrapper for this test. These demonstrate the
  167. framework.KubeDescribe("Kubectl run CronJob", func() {
  168. var nsFlag string
  169. var cjName string
  170. BeforeEach(func() {
  171. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  172. cjName = "e2e-test-echo-cronjob-alpha"
  173. })
  174. AfterEach(func() {
  175. framework.RunKubectlOrDie("delete", "cronjobs", cjName, nsFlag)
  176. })
  177. It("should create a CronJob", func() {
  178. framework.SkipIfMissingResource(f.DynamicClient, CronJobGroupVersionResourceAlpha, f.Namespace.Name)
  179. schedule := "*/5 * * * ?"
  180. framework.RunKubectlOrDie("run", cjName, "--restart=OnFailure", "--generator=cronjob/v2alpha1",
  181. "--schedule="+schedule, "--image="+busyboxImage, nsFlag)
  182. By("verifying the CronJob " + cjName + " was created")
  183. sj, err := c.BatchV1beta1().CronJobs(ns).Get(cjName, metav1.GetOptions{})
  184. if err != nil {
  185. framework.Failf("Failed getting CronJob %s: %v", cjName, err)
  186. }
  187. if sj.Spec.Schedule != schedule {
  188. framework.Failf("Failed creating a CronJob with correct schedule %s", schedule)
  189. }
  190. containers := sj.Spec.JobTemplate.Spec.Template.Spec.Containers
  191. if containers == nil || len(containers) != 1 || containers[0].Image != busyboxImage {
  192. framework.Failf("Failed creating CronJob %s for 1 pod with expected image %s: %#v", cjName, busyboxImage, containers)
  193. }
  194. if sj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure {
  195. framework.Failf("Failed creating a CronJob with correct restart policy for --restart=OnFailure")
  196. }
  197. })
  198. })
  199. })
  200. var _ = SIGDescribe("Kubectl client", func() {
  201. defer GinkgoRecover()
  202. f := framework.NewDefaultFramework("kubectl")
  203. // Reusable cluster state function. This won't be adversely affected by lazy initialization of framework.
  204. clusterState := func() *framework.ClusterVerification {
  205. return f.NewClusterVerification(
  206. f.Namespace,
  207. framework.PodStateVerification{
  208. Selectors: map[string]string{"app": "redis"},
  209. ValidPhases: []v1.PodPhase{v1.PodRunning /*v1.PodPending*/},
  210. })
  211. }
  212. forEachPod := func(podFunc func(p v1.Pod)) {
  213. clusterState().ForEach(podFunc)
  214. }
  215. var c clientset.Interface
  216. var ns string
  217. BeforeEach(func() {
  218. c = f.ClientSet
  219. ns = f.Namespace.Name
  220. })
  221. // Customized Wait / ForEach wrapper for this test. These demonstrate the
  222. // idiomatic way to wrap the ClusterVerification structs for syntactic sugar in large
  223. // test files.
  224. // Print debug info if atLeast Pods are not found before the timeout
  225. waitForOrFailWithDebug := func(atLeast int) {
  226. pods, err := clusterState().WaitFor(atLeast, framework.PodStartTimeout)
  227. if err != nil || len(pods) < atLeast {
  228. // TODO: Generalize integrating debug info into these tests so we always get debug info when we need it
  229. framework.DumpAllNamespaceInfo(f.ClientSet, ns)
  230. framework.Failf("Verified %v of %v pods , error : %v", len(pods), atLeast, err)
  231. }
  232. }
  233. framework.KubeDescribe("Update Demo", func() {
  234. var nautilus, kitten string
  235. BeforeEach(func() {
  236. updateDemoRoot := "test/fixtures/doc-yaml/user-guide/update-demo"
  237. nautilus = substituteImageName(string(generated.ReadOrDie(filepath.Join(updateDemoRoot, "nautilus-rc.yaml.in"))))
  238. kitten = substituteImageName(string(generated.ReadOrDie(filepath.Join(updateDemoRoot, "kitten-rc.yaml.in"))))
  239. })
  240. /*
  241. Release : v1.9
  242. Testname: Kubectl, replication controller
  243. Description: Create a Pod and a container with a given image. Configure replication controller to run 2 replicas. The number of running instances of the Pod MUST equal the number of replicas set on the replication controller which is 2.
  244. */
  245. framework.ConformanceIt("should create and stop a replication controller ", func() {
  246. defer cleanupKubectlInputs(nautilus, ns, updateDemoSelector)
  247. By("creating a replication controller")
  248. framework.RunKubectlOrDieInput(nautilus, "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  249. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  250. })
  251. /*
  252. Release : v1.9
  253. Testname: Kubectl, scale replication controller
  254. Description: Create a Pod and a container with a given image. Configure replication controller to run 2 replicas. The number of running instances of the Pod MUST equal the number of replicas set on the replication controller which is 2. Update the replicaset to 1. Number of running instances of the Pod MUST be 1. Update the replicaset to 2. Number of running instances of the Pod MUST be 2.
  255. */
  256. framework.ConformanceIt("should scale a replication controller ", func() {
  257. defer cleanupKubectlInputs(nautilus, ns, updateDemoSelector)
  258. By("creating a replication controller")
  259. framework.RunKubectlOrDieInput(nautilus, "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  260. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  261. By("scaling down the replication controller")
  262. framework.RunKubectlOrDie("scale", "rc", "update-demo-nautilus", "--replicas=1", "--timeout=5m", fmt.Sprintf("--namespace=%v", ns))
  263. framework.ValidateController(c, nautilusImage, 1, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  264. By("scaling up the replication controller")
  265. framework.RunKubectlOrDie("scale", "rc", "update-demo-nautilus", "--replicas=2", "--timeout=5m", fmt.Sprintf("--namespace=%v", ns))
  266. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  267. })
  268. /*
  269. Release : v1.9
  270. Testname: Kubectl, rolling update replication controller
  271. Description: Create a Pod and a container with a given image. Configure replication controller to run 2 replicas. The number of running instances of the Pod MUST equal the number of replicas set on the replication controller which is 2. Run a rolling update to run a different version of the container. All running instances SHOULD now be running the newer version of the container as part of the rolling update.
  272. */
  273. framework.ConformanceIt("should do a rolling update of a replication controller ", func() {
  274. By("creating the initial replication controller")
  275. framework.RunKubectlOrDieInput(string(nautilus[:]), "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  276. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  277. By("rolling-update to new replication controller")
  278. framework.RunKubectlOrDieInput(string(kitten[:]), "rolling-update", "update-demo-nautilus", "--update-period=1s", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  279. framework.ValidateController(c, kittenImage, 2, "update-demo", updateDemoSelector, getUDData("kitten.jpg", ns), ns)
  280. // Everything will hopefully be cleaned up when the namespace is deleted.
  281. })
  282. })
  283. framework.KubeDescribe("Guestbook application", func() {
  284. forEachGBFile := func(run func(s string)) {
  285. guestbookRoot := "test/e2e/testing-manifests/guestbook"
  286. for _, gbAppFile := range []string{
  287. "redis-slave-service.yaml",
  288. "redis-master-service.yaml",
  289. "frontend-service.yaml",
  290. "frontend-deployment.yaml.in",
  291. "redis-master-deployment.yaml.in",
  292. "redis-slave-deployment.yaml.in",
  293. } {
  294. contents := substituteImageName(string(generated.ReadOrDie(filepath.Join(guestbookRoot, gbAppFile))))
  295. run(contents)
  296. }
  297. }
  298. /*
  299. Release : v1.9
  300. Testname: Kubectl, guestbook application
  301. Description: Create Guestbook application that contains redis server, 2 instances of redis slave, frontend application, frontend service and redis master service and redis slave service. Using frontend service, the test will write an entry into the guestbook application which will store the entry into the backend redis database. Application flow MUST work as expected and the data written MUST be available to read.
  302. */
  303. framework.ConformanceIt("should create and stop a working application ", func() {
  304. defer forEachGBFile(func(contents string) {
  305. cleanupKubectlInputs(contents, ns)
  306. })
  307. By("creating all guestbook components")
  308. forEachGBFile(func(contents string) {
  309. framework.Logf(contents)
  310. framework.RunKubectlOrDieInput(contents, "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  311. })
  312. By("validating guestbook app")
  313. validateGuestbookApp(c, ns)
  314. })
  315. })
  316. framework.KubeDescribe("Simple pod", func() {
  317. podYaml := substituteImageName(string(readTestFileOrDie("pod-with-readiness-probe.yaml.in")))
  318. BeforeEach(func() {
  319. By(fmt.Sprintf("creating the pod from %v", podYaml))
  320. framework.RunKubectlOrDieInput(podYaml, "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  321. Expect(framework.CheckPodsRunningReady(c, ns, []string{simplePodName}, framework.PodStartTimeout)).To(BeTrue())
  322. })
  323. AfterEach(func() {
  324. cleanupKubectlInputs(podYaml, ns, simplePodSelector)
  325. })
  326. It("should support exec", func() {
  327. By("executing a command in the container")
  328. execOutput := framework.RunKubectlOrDie("exec", fmt.Sprintf("--namespace=%v", ns), simplePodName, "echo", "running", "in", "container")
  329. if e, a := "running in container", strings.TrimSpace(execOutput); e != a {
  330. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
  331. }
  332. By("executing a very long command in the container")
  333. veryLongData := make([]rune, 20000)
  334. for i := 0; i < len(veryLongData); i++ {
  335. veryLongData[i] = 'a'
  336. }
  337. execOutput = framework.RunKubectlOrDie("exec", fmt.Sprintf("--namespace=%v", ns), simplePodName, "echo", string(veryLongData))
  338. Expect(string(veryLongData)).To(Equal(strings.TrimSpace(execOutput)), "Unexpected kubectl exec output")
  339. By("executing a command in the container with noninteractive stdin")
  340. execOutput = framework.NewKubectlCommand("exec", fmt.Sprintf("--namespace=%v", ns), "-i", simplePodName, "cat").
  341. WithStdinData("abcd1234").
  342. ExecOrDie()
  343. if e, a := "abcd1234", execOutput; e != a {
  344. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
  345. }
  346. // pretend that we're a user in an interactive shell
  347. r, closer, err := newBlockingReader("echo hi\nexit\n")
  348. if err != nil {
  349. framework.Failf("Error creating blocking reader: %v", err)
  350. }
  351. // NOTE this is solely for test cleanup!
  352. defer closer.Close()
  353. By("executing a command in the container with pseudo-interactive stdin")
  354. execOutput = framework.NewKubectlCommand("exec", fmt.Sprintf("--namespace=%v", ns), "-i", simplePodName, "bash").
  355. WithStdinReader(r).
  356. ExecOrDie()
  357. if e, a := "hi", strings.TrimSpace(execOutput); e != a {
  358. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
  359. }
  360. })
  361. It("should support exec through an HTTP proxy", func() {
  362. // Fail if the variable isn't set
  363. if framework.TestContext.Host == "" {
  364. framework.Failf("--host variable must be set to the full URI to the api server on e2e run.")
  365. }
  366. By("Starting goproxy")
  367. testSrv, proxyLogs := startLocalProxy()
  368. defer testSrv.Close()
  369. proxyAddr := testSrv.URL
  370. for _, proxyVar := range []string{"https_proxy", "HTTPS_PROXY"} {
  371. proxyLogs.Reset()
  372. By("Running kubectl via an HTTP proxy using " + proxyVar)
  373. output := framework.NewKubectlCommand(fmt.Sprintf("--namespace=%s", ns), "exec", "nginx", "echo", "running", "in", "container").
  374. WithEnv(append(os.Environ(), fmt.Sprintf("%s=%s", proxyVar, proxyAddr))).
  375. ExecOrDie()
  376. // Verify we got the normal output captured by the exec server
  377. expectedExecOutput := "running in container\n"
  378. if output != expectedExecOutput {
  379. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", expectedExecOutput, output)
  380. }
  381. // Verify the proxy server logs saw the connection
  382. expectedProxyLog := fmt.Sprintf("Accepting CONNECT to %s", strings.TrimRight(strings.TrimLeft(framework.TestContext.Host, "https://"), "/api"))
  383. proxyLog := proxyLogs.String()
  384. if !strings.Contains(proxyLog, expectedProxyLog) {
  385. framework.Failf("Missing expected log result on proxy server for %s. Expected: %q, got %q", proxyVar, expectedProxyLog, proxyLog)
  386. }
  387. }
  388. })
  389. It("should support exec through kubectl proxy", func() {
  390. // Fail if the variable isn't set
  391. if framework.TestContext.Host == "" {
  392. framework.Failf("--host variable must be set to the full URI to the api server on e2e run.")
  393. }
  394. By("Starting kubectl proxy")
  395. port, proxyCmd, err := startProxyServer()
  396. framework.ExpectNoError(err)
  397. defer framework.TryKill(proxyCmd)
  398. //proxyLogs.Reset()
  399. host := fmt.Sprintf("--server=http://127.0.0.1:%d", port)
  400. By("Running kubectl via kubectl proxy using " + host)
  401. output := framework.NewKubectlCommand(
  402. host, fmt.Sprintf("--namespace=%s", ns),
  403. "exec", "nginx", "echo", "running", "in", "container",
  404. ).ExecOrDie()
  405. // Verify we got the normal output captured by the exec server
  406. expectedExecOutput := "running in container\n"
  407. if output != expectedExecOutput {
  408. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", expectedExecOutput, output)
  409. }
  410. })
  411. It("should return command exit codes", func() {
  412. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  413. By("execing into a container with a successful command")
  414. _, err := framework.NewKubectlCommand(nsFlag, "exec", "nginx", "--", "/bin/sh", "-c", "exit 0").Exec()
  415. framework.ExpectNoError(err)
  416. By("execing into a container with a failing command")
  417. _, err = framework.NewKubectlCommand(nsFlag, "exec", "nginx", "--", "/bin/sh", "-c", "exit 42").Exec()
  418. ee, ok := err.(uexec.ExitError)
  419. Expect(ok).To(Equal(true))
  420. Expect(ee.ExitStatus()).To(Equal(42))
  421. By("running a successful command")
  422. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=Never", "success", "--", "/bin/sh", "-c", "exit 0").Exec()
  423. framework.ExpectNoError(err)
  424. By("running a failing command")
  425. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=Never", "failure-1", "--", "/bin/sh", "-c", "exit 42").Exec()
  426. ee, ok = err.(uexec.ExitError)
  427. Expect(ok).To(Equal(true))
  428. Expect(ee.ExitStatus()).To(Equal(42))
  429. By("running a failing command without --restart=Never")
  430. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=OnFailure", "failure-2", "--", "/bin/sh", "-c", "cat && exit 42").
  431. WithStdinData("abcd1234").
  432. Exec()
  433. framework.ExpectNoError(err)
  434. By("running a failing command without --restart=Never, but with --rm")
  435. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=OnFailure", "--rm", "failure-3", "--", "/bin/sh", "-c", "cat && exit 42").
  436. WithStdinData("abcd1234").
  437. Exec()
  438. framework.ExpectNoError(err)
  439. framework.WaitForPodToDisappear(f.ClientSet, ns, "failure-3", labels.Everything(), 2*time.Second, wait.ForeverTestTimeout)
  440. By("running a failing command with --leave-stdin-open")
  441. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=Never", "failure-4", "--leave-stdin-open", "--", "/bin/sh", "-c", "exit 42").
  442. WithStdinData("abcd1234").
  443. Exec()
  444. framework.ExpectNoError(err)
  445. })
  446. It("should support inline execution and attach", func() {
  447. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  448. By("executing a command with run and attach with stdin")
  449. runOutput := framework.NewKubectlCommand(nsFlag, "run", "run-test", "--image="+busyboxImage, "--restart=OnFailure", "--attach=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
  450. WithStdinData("abcd1234").
  451. ExecOrDie()
  452. Expect(runOutput).To(ContainSubstring("abcd1234"))
  453. Expect(runOutput).To(ContainSubstring("stdin closed"))
  454. Expect(c.BatchV1().Jobs(ns).Delete("run-test", nil)).To(BeNil())
  455. By("executing a command with run and attach without stdin")
  456. runOutput = framework.NewKubectlCommand(fmt.Sprintf("--namespace=%v", ns), "run", "run-test-2", "--image="+busyboxImage, "--restart=OnFailure", "--attach=true", "--leave-stdin-open=true", "--", "sh", "-c", "cat && echo 'stdin closed'").
  457. WithStdinData("abcd1234").
  458. ExecOrDie()
  459. Expect(runOutput).ToNot(ContainSubstring("abcd1234"))
  460. Expect(runOutput).To(ContainSubstring("stdin closed"))
  461. Expect(c.BatchV1().Jobs(ns).Delete("run-test-2", nil)).To(BeNil())
  462. By("executing a command with run and attach with stdin with open stdin should remain running")
  463. runOutput = framework.NewKubectlCommand(nsFlag, "run", "run-test-3", "--image="+busyboxImage, "--restart=OnFailure", "--attach=true", "--leave-stdin-open=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
  464. WithStdinData("abcd1234\n").
  465. ExecOrDie()
  466. Expect(runOutput).ToNot(ContainSubstring("stdin closed"))
  467. g := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }
  468. runTestPod, _, err := polymorphichelpers.GetFirstPod(f.InternalClientset.Core(), ns, "run=run-test-3", 1*time.Minute, g)
  469. if err != nil {
  470. os.Exit(1)
  471. }
  472. if !framework.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, time.Minute) {
  473. framework.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")
  474. }
  475. // NOTE: we cannot guarantee our output showed up in the container logs before stdin was closed, so we have
  476. // to loop test.
  477. err = wait.PollImmediate(time.Second, time.Minute, func() (bool, error) {
  478. if !framework.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, 1*time.Second) {
  479. framework.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")
  480. }
  481. logOutput := framework.RunKubectlOrDie(nsFlag, "logs", runTestPod.Name)
  482. Expect(logOutput).ToNot(ContainSubstring("stdin closed"))
  483. return strings.Contains(logOutput, "abcd1234"), nil
  484. })
  485. if err != nil {
  486. os.Exit(1)
  487. }
  488. Expect(err).To(BeNil())
  489. Expect(c.BatchV1().Jobs(ns).Delete("run-test-3", nil)).To(BeNil())
  490. })
  491. It("should support port-forward", func() {
  492. By("forwarding the container port to a local port")
  493. cmd := runPortForward(ns, simplePodName, simplePodPort)
  494. defer cmd.Stop()
  495. By("curling local port output")
  496. localAddr := fmt.Sprintf("http://localhost:%d", cmd.port)
  497. body, err := curl(localAddr)
  498. framework.Logf("got: %s", body)
  499. if err != nil {
  500. framework.Failf("Failed http.Get of forwarded port (%s): %v", localAddr, err)
  501. }
  502. if !strings.Contains(body, nginxDefaultOutput) {
  503. framework.Failf("Container port output missing expected value. Wanted:'%s', got: %s", nginxDefaultOutput, body)
  504. }
  505. })
  506. It("should handle in-cluster config", func() {
  507. By("adding rbac permissions")
  508. // grant the view permission widely to allow inspection of the `invalid` namespace and the default namespace
  509. framework.BindClusterRole(f.ClientSet.RbacV1beta1(), "view", f.Namespace.Name,
  510. rbacv1beta1.Subject{Kind: rbacv1beta1.ServiceAccountKind, Namespace: f.Namespace.Name, Name: "default"})
  511. err := framework.WaitForAuthorizationUpdate(f.ClientSet.AuthorizationV1beta1(),
  512. serviceaccount.MakeUsername(f.Namespace.Name, "default"),
  513. f.Namespace.Name, "list", schema.GroupResource{Resource: "pods"}, true)
  514. framework.ExpectNoError(err)
  515. By("overriding icc with values provided by flags")
  516. kubectlPath := framework.TestContext.KubectlPath
  517. // we need the actual kubectl binary, not the script wrapper
  518. kubectlPathNormalizer := exec.Command("which", kubectlPath)
  519. if strings.HasSuffix(kubectlPath, "kubectl.sh") {
  520. kubectlPathNormalizer = exec.Command(kubectlPath, "path")
  521. }
  522. kubectlPathNormalized, err := kubectlPathNormalizer.Output()
  523. framework.ExpectNoError(err)
  524. kubectlPath = strings.TrimSpace(string(kubectlPathNormalized))
  525. inClusterHost := strings.TrimSpace(framework.RunHostCmdOrDie(ns, simplePodName, "printenv KUBERNETES_SERVICE_HOST"))
  526. inClusterPort := strings.TrimSpace(framework.RunHostCmdOrDie(ns, simplePodName, "printenv KUBERNETES_SERVICE_PORT"))
  527. framework.Logf("copying %s to the %s pod", kubectlPath, simplePodName)
  528. framework.RunKubectlOrDie("cp", kubectlPath, ns+"/"+simplePodName+":/tmp/")
  529. // Build a kubeconfig file that will make use of the injected ca and token,
  530. // but point at the DNS host and the default namespace
  531. tmpDir, err := ioutil.TempDir("", "icc-override")
  532. overrideKubeconfigName := "icc-override.kubeconfig"
  533. framework.ExpectNoError(err)
  534. defer func() { os.Remove(tmpDir) }()
  535. framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, overrideKubeconfigName), []byte(`
  536. kind: Config
  537. apiVersion: v1
  538. clusters:
  539. - cluster:
  540. api-version: v1
  541. server: https://kubernetes.default.svc:443
  542. certificate-authority: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
  543. name: kubeconfig-cluster
  544. contexts:
  545. - context:
  546. cluster: kubeconfig-cluster
  547. namespace: default
  548. user: kubeconfig-user
  549. name: kubeconfig-context
  550. current-context: kubeconfig-context
  551. users:
  552. - name: kubeconfig-user
  553. user:
  554. tokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
  555. `), os.FileMode(0755)))
  556. framework.Logf("copying override kubeconfig to the %s pod", simplePodName)
  557. framework.RunKubectlOrDie("cp", filepath.Join(tmpDir, overrideKubeconfigName), ns+"/"+simplePodName+":/tmp/")
  558. framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, "invalid-configmap-with-namespace.yaml"), []byte(`
  559. kind: ConfigMap
  560. apiVersion: v1
  561. metadata:
  562. name: "configmap with namespace and invalid name"
  563. namespace: configmap-namespace
  564. `), os.FileMode(0755)))
  565. framework.ExpectNoError(ioutil.WriteFile(filepath.Join(tmpDir, "invalid-configmap-without-namespace.yaml"), []byte(`
  566. kind: ConfigMap
  567. apiVersion: v1
  568. metadata:
  569. name: "configmap without namespace and invalid name"
  570. `), os.FileMode(0755)))
  571. framework.Logf("copying configmap manifests to the %s pod", simplePodName)
  572. framework.RunKubectlOrDie("cp", filepath.Join(tmpDir, "invalid-configmap-with-namespace.yaml"), ns+"/"+simplePodName+":/tmp/")
  573. framework.RunKubectlOrDie("cp", filepath.Join(tmpDir, "invalid-configmap-without-namespace.yaml"), ns+"/"+simplePodName+":/tmp/")
  574. By("getting pods with in-cluster configs")
  575. execOutput := framework.RunHostCmdOrDie(ns, simplePodName, "/tmp/kubectl get pods --v=7 2>&1")
  576. Expect(execOutput).To(MatchRegexp("nginx +1/1 +Running"))
  577. Expect(execOutput).To(ContainSubstring("Using in-cluster namespace"))
  578. Expect(execOutput).To(ContainSubstring("Using in-cluster configuration"))
  579. By("creating an object containing a namespace with in-cluster config")
  580. _, err = framework.RunHostCmd(ns, simplePodName, "/tmp/kubectl create -f /tmp/invalid-configmap-with-namespace.yaml --v=7 2>&1")
  581. Expect(err).To(ContainSubstring("Using in-cluster namespace"))
  582. Expect(err).To(ContainSubstring("Using in-cluster configuration"))
  583. Expect(err).To(ContainSubstring(fmt.Sprintf("POST https://%s:%s/api/v1/namespaces/configmap-namespace/configmaps", inClusterHost, inClusterPort)))
  584. By("creating an object not containing a namespace with in-cluster config")
  585. _, err = framework.RunHostCmd(ns, simplePodName, "/tmp/kubectl create -f /tmp/invalid-configmap-without-namespace.yaml --v=7 2>&1")
  586. Expect(err).To(ContainSubstring("Using in-cluster namespace"))
  587. Expect(err).To(ContainSubstring("Using in-cluster configuration"))
  588. Expect(err).To(ContainSubstring(fmt.Sprintf("POST https://%s:%s/api/v1/namespaces/%s/configmaps", inClusterHost, inClusterPort, f.Namespace.Name)))
  589. By("trying to use kubectl with invalid token")
  590. _, err = framework.RunHostCmd(ns, simplePodName, "/tmp/kubectl get pods --token=invalid --v=7 2>&1")
  591. framework.Logf("got err %v", err)
  592. Expect(err).To(HaveOccurred())
  593. Expect(err).To(ContainSubstring("Using in-cluster namespace"))
  594. Expect(err).To(ContainSubstring("Using in-cluster configuration"))
  595. Expect(err).To(ContainSubstring("Authorization: Bearer invalid"))
  596. Expect(err).To(ContainSubstring("Response Status: 401 Unauthorized"))
  597. By("trying to use kubectl with invalid server")
  598. _, err = framework.RunHostCmd(ns, simplePodName, "/tmp/kubectl get pods --server=invalid --v=6 2>&1")
  599. framework.Logf("got err %v", err)
  600. Expect(err).To(HaveOccurred())
  601. Expect(err).To(ContainSubstring("Unable to connect to the server"))
  602. Expect(err).To(ContainSubstring("GET http://invalid/api"))
  603. By("trying to use kubectl with invalid namespace")
  604. execOutput = framework.RunHostCmdOrDie(ns, simplePodName, "/tmp/kubectl get pods --namespace=invalid --v=6 2>&1")
  605. Expect(execOutput).To(ContainSubstring("No resources found"))
  606. Expect(execOutput).ToNot(ContainSubstring("Using in-cluster namespace"))
  607. Expect(execOutput).To(ContainSubstring("Using in-cluster configuration"))
  608. Expect(execOutput).To(MatchRegexp(fmt.Sprintf("GET http[s]?://%s:%s/api/v1/namespaces/invalid/pods", inClusterHost, inClusterPort)))
  609. By("trying to use kubectl with kubeconfig")
  610. execOutput = framework.RunHostCmdOrDie(ns, simplePodName, "/tmp/kubectl get pods --kubeconfig=/tmp/"+overrideKubeconfigName+" --v=6 2>&1")
  611. Expect(execOutput).ToNot(ContainSubstring("Using in-cluster namespace"))
  612. Expect(execOutput).ToNot(ContainSubstring("Using in-cluster configuration"))
  613. Expect(execOutput).To(ContainSubstring("GET https://kubernetes.default.svc:443/api/v1/namespaces/default/pods"))
  614. })
  615. })
  616. framework.KubeDescribe("Kubectl api-versions", func() {
  617. /*
  618. Release : v1.9
  619. Testname: Kubectl, check version v1
  620. Description: Run kubectl to get api versions, output MUST contain returned versions with ‘v1’ listed.
  621. */
  622. framework.ConformanceIt("should check if v1 is in available api versions ", func() {
  623. By("validating api versions")
  624. output := framework.RunKubectlOrDie("api-versions")
  625. if !strings.Contains(output, "v1") {
  626. framework.Failf("No v1 in kubectl api-versions")
  627. }
  628. })
  629. })
  630. framework.KubeDescribe("Kubectl apply", func() {
  631. It("should apply a new configuration to an existing RC", func() {
  632. controllerJson := substituteImageName(string(readTestFileOrDie(redisControllerFilename)))
  633. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  634. By("creating Redis RC")
  635. framework.RunKubectlOrDieInput(controllerJson, "create", "-f", "-", nsFlag)
  636. By("applying a modified configuration")
  637. stdin := modifyReplicationControllerConfiguration(controllerJson)
  638. framework.NewKubectlCommand("apply", "-f", "-", nsFlag).
  639. WithStdinReader(stdin).
  640. ExecOrDie()
  641. By("checking the result")
  642. forEachReplicationController(c, ns, "app", "redis", validateReplicationControllerConfiguration)
  643. })
  644. It("should reuse port when apply to an existing SVC", func() {
  645. serviceJson := readTestFileOrDie(redisServiceFilename)
  646. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  647. By("creating Redis SVC")
  648. framework.RunKubectlOrDieInput(string(serviceJson[:]), "create", "-f", "-", nsFlag)
  649. By("getting the original port")
  650. originalNodePort := framework.RunKubectlOrDie("get", "service", "redis-master", nsFlag, "-o", "jsonpath={.spec.ports[0].port}")
  651. By("applying the same configuration")
  652. framework.RunKubectlOrDieInput(string(serviceJson[:]), "apply", "-f", "-", nsFlag)
  653. By("getting the port after applying configuration")
  654. currentNodePort := framework.RunKubectlOrDie("get", "service", "redis-master", nsFlag, "-o", "jsonpath={.spec.ports[0].port}")
  655. By("checking the result")
  656. if originalNodePort != currentNodePort {
  657. framework.Failf("port should keep the same")
  658. }
  659. })
  660. It("apply set/view last-applied", func() {
  661. deployment1Yaml := substituteImageName(string(readTestFileOrDie(nginxDeployment1Filename)))
  662. deployment2Yaml := substituteImageName(string(readTestFileOrDie(nginxDeployment2Filename)))
  663. deployment3Yaml := substituteImageName(string(readTestFileOrDie(nginxDeployment3Filename)))
  664. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  665. By("deployment replicas number is 2")
  666. framework.RunKubectlOrDieInput(deployment1Yaml, "apply", "-f", "-", nsFlag)
  667. By("check the last-applied matches expectations annotations")
  668. output := framework.RunKubectlOrDieInput(deployment1Yaml, "apply", "view-last-applied", "-f", "-", nsFlag, "-o", "json")
  669. requiredString := "\"replicas\": 2"
  670. if !strings.Contains(output, requiredString) {
  671. framework.Failf("Missing %s in kubectl view-last-applied", requiredString)
  672. }
  673. By("apply file doesn't have replicas")
  674. framework.RunKubectlOrDieInput(deployment2Yaml, "apply", "set-last-applied", "-f", "-", nsFlag)
  675. By("check last-applied has been updated, annotations doesn't replicas")
  676. output = framework.RunKubectlOrDieInput(deployment1Yaml, "apply", "view-last-applied", "-f", "-", nsFlag, "-o", "json")
  677. requiredString = "\"replicas\": 2"
  678. if strings.Contains(output, requiredString) {
  679. framework.Failf("Missing %s in kubectl view-last-applied", requiredString)
  680. }
  681. By("scale set replicas to 3")
  682. nginxDeploy := "nginx-deployment"
  683. framework.RunKubectlOrDie("scale", "deployment", nginxDeploy, "--replicas=3", nsFlag)
  684. By("apply file doesn't have replicas but image changed")
  685. framework.RunKubectlOrDieInput(deployment3Yaml, "apply", "-f", "-", nsFlag)
  686. By("verify replicas still is 3 and image has been updated")
  687. output = framework.RunKubectlOrDieInput(deployment3Yaml, "get", "-f", "-", nsFlag, "-o", "json")
  688. requiredItems := []string{"\"replicas\": 3", imageutils.GetE2EImage(imageutils.NginxSlim)}
  689. for _, item := range requiredItems {
  690. if !strings.Contains(output, item) {
  691. framework.Failf("Missing %s in kubectl apply", item)
  692. }
  693. }
  694. })
  695. })
  696. framework.KubeDescribe("Kubectl cluster-info", func() {
  697. /*
  698. Release : v1.9
  699. Testname: Kubectl, cluster info
  700. Description: Call kubectl to get cluster-info, output MUST contain cluster-info returned and Kubernetes Master SHOULD be running.
  701. */
  702. framework.ConformanceIt("should check if Kubernetes master services is included in cluster-info ", func() {
  703. By("validating cluster-info")
  704. output := framework.RunKubectlOrDie("cluster-info")
  705. // Can't check exact strings due to terminal control commands (colors)
  706. requiredItems := []string{"Kubernetes master", "is running at"}
  707. if framework.ProviderIs("gce", "gke") {
  708. requiredItems = append(requiredItems, "Heapster")
  709. }
  710. for _, item := range requiredItems {
  711. if !strings.Contains(output, item) {
  712. framework.Failf("Missing %s in kubectl cluster-info", item)
  713. }
  714. }
  715. })
  716. })
  717. framework.KubeDescribe("Kubectl describe", func() {
  718. /*
  719. Release : v1.9
  720. Testname: Kubectl, describe pod or rc
  721. Description: Deploy a redis controller and a redis service. Kubectl describe pods SHOULD return the name, namespace, labels, state and other information as expected. Kubectl describe on rc, service, node and namespace SHOULD also return proper information.
  722. */
  723. framework.ConformanceIt("should check if kubectl describe prints relevant information for rc and pods ", func() {
  724. kv, err := framework.KubectlVersion()
  725. Expect(err).NotTo(HaveOccurred())
  726. framework.SkipUnlessServerVersionGTE(kv, c.Discovery())
  727. controllerJson := substituteImageName(string(readTestFileOrDie(redisControllerFilename)))
  728. serviceJson := readTestFileOrDie(redisServiceFilename)
  729. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  730. framework.RunKubectlOrDieInput(controllerJson, "create", "-f", "-", nsFlag)
  731. framework.RunKubectlOrDieInput(string(serviceJson[:]), "create", "-f", "-", nsFlag)
  732. By("Waiting for Redis master to start.")
  733. waitForOrFailWithDebug(1)
  734. // Pod
  735. forEachPod(func(pod v1.Pod) {
  736. output := framework.RunKubectlOrDie("describe", "pod", pod.Name, nsFlag)
  737. requiredStrings := [][]string{
  738. {"Name:", "redis-master-"},
  739. {"Namespace:", ns},
  740. {"Node:"},
  741. {"Labels:", "app=redis"},
  742. {"role=master"},
  743. {"Annotations:"},
  744. {"Status:", "Running"},
  745. {"IP:"},
  746. {"Controlled By:", "ReplicationController/redis-master"},
  747. {"Image:", redisImage},
  748. {"State:", "Running"},
  749. {"QoS Class:", "BestEffort"},
  750. }
  751. checkOutput(output, requiredStrings)
  752. })
  753. // Rc
  754. requiredStrings := [][]string{
  755. {"Name:", "redis-master"},
  756. {"Namespace:", ns},
  757. {"Selector:", "app=redis,role=master"},
  758. {"Labels:", "app=redis"},
  759. {"role=master"},
  760. {"Annotations:"},
  761. {"Replicas:", "1 current", "1 desired"},
  762. {"Pods Status:", "1 Running", "0 Waiting", "0 Succeeded", "0 Failed"},
  763. {"Pod Template:"},
  764. {"Image:", redisImage},
  765. {"Events:"}}
  766. checkKubectlOutputWithRetry(requiredStrings, "describe", "rc", "redis-master", nsFlag)
  767. // Service
  768. output := framework.RunKubectlOrDie("describe", "service", "redis-master", nsFlag)
  769. requiredStrings = [][]string{
  770. {"Name:", "redis-master"},
  771. {"Namespace:", ns},
  772. {"Labels:", "app=redis"},
  773. {"role=master"},
  774. {"Annotations:"},
  775. {"Selector:", "app=redis", "role=master"},
  776. {"Type:", "ClusterIP"},
  777. {"IP:"},
  778. {"Port:", "<unset>", "6379/TCP"},
  779. {"Endpoints:"},
  780. {"Session Affinity:", "None"}}
  781. checkOutput(output, requiredStrings)
  782. // Node
  783. // It should be OK to list unschedulable Nodes here.
  784. nodes, err := c.CoreV1().Nodes().List(metav1.ListOptions{})
  785. Expect(err).NotTo(HaveOccurred())
  786. node := nodes.Items[0]
  787. output = framework.RunKubectlOrDie("describe", "node", node.Name)
  788. requiredStrings = [][]string{
  789. {"Name:", node.Name},
  790. {"Labels:"},
  791. {"Annotations:"},
  792. {"CreationTimestamp:"},
  793. {"Conditions:"},
  794. {"Type", "Status", "LastHeartbeatTime", "LastTransitionTime", "Reason", "Message"},
  795. {"Addresses:"},
  796. {"Capacity:"},
  797. {"Version:"},
  798. {"Kernel Version:"},
  799. {"OS Image:"},
  800. {"Container Runtime Version:"},
  801. {"Kubelet Version:"},
  802. {"Kube-Proxy Version:"},
  803. {"Pods:"}}
  804. checkOutput(output, requiredStrings)
  805. // Namespace
  806. output = framework.RunKubectlOrDie("describe", "namespace", ns)
  807. requiredStrings = [][]string{
  808. {"Name:", ns},
  809. {"Labels:"},
  810. {"Annotations:"},
  811. {"Status:", "Active"}}
  812. checkOutput(output, requiredStrings)
  813. // Quota and limitrange are skipped for now.
  814. })
  815. })
  816. framework.KubeDescribe("Kubectl expose", func() {
  817. /*
  818. Release : v1.9
  819. Testname: Kubectl, create service, replication controller
  820. Description: Create a Pod running redis master listening to port 6379. Using kubectl expose the redis master replication controllers at port 1234. Validate that the replication controller is listening on port 1234 and the target port is set to 6379, port that redis master is listening. Using kubectl expose the redis master as a service at port 2345. The service MUST be listening on port 2345 and the target port is set to 6379, port that redis master is listening.
  821. */
  822. framework.ConformanceIt("should create services for rc ", func() {
  823. controllerJson := substituteImageName(string(readTestFileOrDie(redisControllerFilename)))
  824. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  825. redisPort := 6379
  826. By("creating Redis RC")
  827. framework.Logf("namespace %v", ns)
  828. framework.RunKubectlOrDieInput(controllerJson, "create", "-f", "-", nsFlag)
  829. // It may take a while for the pods to get registered in some cases, wait to be sure.
  830. By("Waiting for Redis master to start.")
  831. waitForOrFailWithDebug(1)
  832. forEachPod(func(pod v1.Pod) {
  833. framework.Logf("wait on redis-master startup in %v ", ns)
  834. framework.LookForStringInLog(ns, pod.Name, "redis-master", "The server is now ready to accept connections", framework.PodStartTimeout)
  835. })
  836. validateService := func(name string, servicePort int, timeout time.Duration) {
  837. err := wait.Poll(framework.Poll, timeout, func() (bool, error) {
  838. endpoints, err := c.CoreV1().Endpoints(ns).Get(name, metav1.GetOptions{})
  839. if err != nil {
  840. // log the real error
  841. framework.Logf("Get endpoints failed (interval %v): %v", framework.Poll, err)
  842. // if the error is API not found or could not find default credentials or TLS handshake timeout, try again
  843. if apierrs.IsNotFound(err) ||
  844. apierrs.IsUnauthorized(err) ||
  845. apierrs.IsServerTimeout(err) {
  846. err = nil
  847. }
  848. return false, err
  849. }
  850. uidToPort := framework.GetContainerPortsByPodUID(endpoints)
  851. if len(uidToPort) == 0 {
  852. framework.Logf("No endpoint found, retrying")
  853. return false, nil
  854. }
  855. if len(uidToPort) > 1 {
  856. framework.Failf("Too many endpoints found")
  857. }
  858. for _, port := range uidToPort {
  859. if port[0] != redisPort {
  860. framework.Failf("Wrong endpoint port: %d", port[0])
  861. }
  862. }
  863. return true, nil
  864. })
  865. Expect(err).NotTo(HaveOccurred())
  866. service, err := c.CoreV1().Services(ns).Get(name, metav1.GetOptions{})
  867. Expect(err).NotTo(HaveOccurred())
  868. if len(service.Spec.Ports) != 1 {
  869. framework.Failf("1 port is expected")
  870. }
  871. port := service.Spec.Ports[0]
  872. if port.Port != int32(servicePort) {
  873. framework.Failf("Wrong service port: %d", port.Port)
  874. }
  875. if port.TargetPort.IntValue() != redisPort {
  876. framework.Failf("Wrong target port: %d", port.TargetPort.IntValue())
  877. }
  878. }
  879. By("exposing RC")
  880. framework.RunKubectlOrDie("expose", "rc", "redis-master", "--name=rm2", "--port=1234", fmt.Sprintf("--target-port=%d", redisPort), nsFlag)
  881. framework.WaitForService(c, ns, "rm2", true, framework.Poll, framework.ServiceStartTimeout)
  882. validateService("rm2", 1234, framework.ServiceStartTimeout)
  883. By("exposing service")
  884. framework.RunKubectlOrDie("expose", "service", "rm2", "--name=rm3", "--port=2345", fmt.Sprintf("--target-port=%d", redisPort), nsFlag)
  885. framework.WaitForService(c, ns, "rm3", true, framework.Poll, framework.ServiceStartTimeout)
  886. validateService("rm3", 2345, framework.ServiceStartTimeout)
  887. })
  888. })
  889. framework.KubeDescribe("Kubectl label", func() {
  890. podYaml := substituteImageName(string(readTestFileOrDie("pause-pod.yaml.in")))
  891. var nsFlag string
  892. BeforeEach(func() {
  893. By("creating the pod")
  894. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  895. framework.RunKubectlOrDieInput(podYaml, "create", "-f", "-", nsFlag)
  896. Expect(framework.CheckPodsRunningReady(c, ns, []string{pausePodName}, framework.PodStartTimeout)).To(BeTrue())
  897. })
  898. AfterEach(func() {
  899. cleanupKubectlInputs(podYaml, ns, pausePodSelector)
  900. })
  901. /*
  902. Release : v1.9
  903. Testname: Kubectl, label update
  904. Description: When a Pod is running, update a Label using ‘kubectl label’ command. The label MUST be created in the Pod. A ‘kubectl get pod’ with -l option on the container MUST verify that the label can be read back. Use ‘kubectl label label-’ to remove the label. Kubetctl get pod’ with -l option SHOULD no list the deleted label as the label is removed.
  905. */
  906. framework.ConformanceIt("should update the label on a resource ", func() {
  907. labelName := "testing-label"
  908. labelValue := "testing-label-value"
  909. By("adding the label " + labelName + " with value " + labelValue + " to a pod")
  910. framework.RunKubectlOrDie("label", "pods", pausePodName, labelName+"="+labelValue, nsFlag)
  911. By("verifying the pod has the label " + labelName + " with the value " + labelValue)
  912. output := framework.RunKubectlOrDie("get", "pod", pausePodName, "-L", labelName, nsFlag)
  913. if !strings.Contains(output, labelValue) {
  914. framework.Failf("Failed updating label " + labelName + " to the pod " + pausePodName)
  915. }
  916. By("removing the label " + labelName + " of a pod")
  917. framework.RunKubectlOrDie("label", "pods", pausePodName, labelName+"-", nsFlag)
  918. By("verifying the pod doesn't have the label " + labelName)
  919. output = framework.RunKubectlOrDie("get", "pod", pausePodName, "-L", labelName, nsFlag)
  920. if strings.Contains(output, labelValue) {
  921. framework.Failf("Failed removing label " + labelName + " of the pod " + pausePodName)
  922. }
  923. })
  924. })
  925. framework.KubeDescribe("Kubectl logs", func() {
  926. var nsFlag string
  927. rc := substituteImageName(string(readTestFileOrDie(redisControllerFilename)))
  928. containerName := "redis-master"
  929. BeforeEach(func() {
  930. By("creating an rc")
  931. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  932. framework.RunKubectlOrDieInput(rc, "create", "-f", "-", nsFlag)
  933. })
  934. AfterEach(func() {
  935. cleanupKubectlInputs(rc, ns, simplePodSelector)
  936. })
  937. /*
  938. Release : v1.9
  939. Testname: Kubectl, logs
  940. Description: When a Pod is running then it MUST generate logs.
  941. Starting a Pod should have a log line indicating the the server is running and ready to accept connections. Also log command options MUST work as expected and described below.
  942. ‘kubectl log -tail=1’ should generate a output of one line, the last line in the log.
  943. ‘kubectl --limit-bytes=1’ should generate a single byte output.
  944. ‘kubectl --tail=1 --timestamp should genrate one line with timestamp in RFC3339 format
  945. ‘kubectl --since=1s’ should output logs that are only 1 second older from now
  946. ‘kubectl --since=24h’ should output logs that are only 1 day older from now
  947. */
  948. framework.ConformanceIt("should be able to retrieve and filter logs ", func() {
  949. // Split("something\n", "\n") returns ["something", ""], so
  950. // strip trailing newline first
  951. lines := func(out string) []string {
  952. return strings.Split(strings.TrimRight(out, "\n"), "\n")
  953. }
  954. By("Waiting for Redis master to start.")
  955. waitForOrFailWithDebug(1)
  956. forEachPod(func(pod v1.Pod) {
  957. By("checking for a matching strings")
  958. _, err := framework.LookForStringInLog(ns, pod.Name, containerName, "The server is now ready to accept connections", framework.PodStartTimeout)
  959. Expect(err).NotTo(HaveOccurred())
  960. By("limiting log lines")
  961. out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--tail=1")
  962. Expect(len(out)).NotTo(BeZero())
  963. Expect(len(lines(out))).To(Equal(1))
  964. By("limiting log bytes")
  965. out = framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--limit-bytes=1")
  966. Expect(len(lines(out))).To(Equal(1))
  967. Expect(len(out)).To(Equal(1))
  968. By("exposing timestamps")
  969. out = framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--tail=1", "--timestamps")
  970. l := lines(out)
  971. Expect(len(l)).To(Equal(1))
  972. words := strings.Split(l[0], " ")
  973. Expect(len(words)).To(BeNumerically(">", 1))
  974. if _, err := time.Parse(time.RFC3339Nano, words[0]); err != nil {
  975. if _, err := time.Parse(time.RFC3339, words[0]); err != nil {
  976. framework.Failf("expected %q to be RFC3339 or RFC3339Nano", words[0])
  977. }
  978. }
  979. By("restricting to a time range")
  980. // Note: we must wait at least two seconds,
  981. // because the granularity is only 1 second and
  982. // it could end up rounding the wrong way.
  983. time.Sleep(2500 * time.Millisecond) // ensure that startup logs on the node are seen as older than 1s
  984. recent_out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--since=1s")
  985. recent := len(strings.Split(recent_out, "\n"))
  986. older_out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--since=24h")
  987. older := len(strings.Split(older_out, "\n"))
  988. Expect(recent).To(BeNumerically("<", older), "expected recent(%v) to be less than older(%v)\nrecent lines:\n%v\nolder lines:\n%v\n", recent, older, recent_out, older_out)
  989. })
  990. })
  991. })
  992. framework.KubeDescribe("Kubectl patch", func() {
  993. /*
  994. Release : v1.9
  995. Testname: Kubectl, patch to annotate
  996. Description: Start running a redis master and a replication controller. When the pod is running, using ‘kubectl patch’ command add annotations. The annotation MUST be added to running pods and SHOULD be able to read added annotations from each of the Pods running under the replication controller.
  997. */
  998. framework.ConformanceIt("should add annotations for pods in rc ", func() {
  999. controllerJson := substituteImageName(string(readTestFileOrDie(redisControllerFilename)))
  1000. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1001. By("creating Redis RC")
  1002. framework.RunKubectlOrDieInput(controllerJson, "create", "-f", "-", nsFlag)
  1003. By("Waiting for Redis master to start.")
  1004. waitForOrFailWithDebug(1)
  1005. By("patching all pods")
  1006. forEachPod(func(pod v1.Pod) {
  1007. framework.RunKubectlOrDie("patch", "pod", pod.Name, nsFlag, "-p", "{\"metadata\":{\"annotations\":{\"x\":\"y\"}}}")
  1008. })
  1009. By("checking annotations")
  1010. forEachPod(func(pod v1.Pod) {
  1011. found := false
  1012. for key, val := range pod.Annotations {
  1013. if key == "x" && val == "y" {
  1014. found = true
  1015. break
  1016. }
  1017. }
  1018. if !found {
  1019. framework.Failf("Added annotation not found")
  1020. }
  1021. })
  1022. })
  1023. })
  1024. framework.KubeDescribe("Kubectl version", func() {
  1025. /*
  1026. Release : v1.9
  1027. Testname: Kubectl, version
  1028. Description: The command ‘kubectl version’ MUST return the major, minor versions, GitCommit, etc of the the Client and the Server that the kubectl is configured to connect to.
  1029. */
  1030. framework.ConformanceIt("should check is all data is printed ", func() {
  1031. version := framework.RunKubectlOrDie("version")
  1032. requiredItems := []string{"Client Version:", "Server Version:", "Major:", "Minor:", "GitCommit:"}
  1033. for _, item := range requiredItems {
  1034. if !strings.Contains(version, item) {
  1035. framework.Failf("Required item %s not found in %s", item, version)
  1036. }
  1037. }
  1038. })
  1039. })
  1040. framework.KubeDescribe("Kubectl run default", func() {
  1041. var nsFlag string
  1042. var name string
  1043. var cleanUp func()
  1044. BeforeEach(func() {
  1045. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1046. name = "e2e-test-nginx-deployment"
  1047. cleanUp = func() { framework.RunKubectlOrDie("delete", "deployment", name, nsFlag) }
  1048. })
  1049. AfterEach(func() {
  1050. cleanUp()
  1051. })
  1052. /*
  1053. Release : v1.9
  1054. Testname: Kubectl, run default
  1055. Description: Command ‘kubectl run’ MUST create a running pod with possible replicas given a image using the option --image=’nginx’. The running Pod SHOULD have one container and the container SHOULD be running the image specified in the ‘run’ command.
  1056. */
  1057. framework.ConformanceIt("should create an rc or deployment from an image ", func() {
  1058. By("running the image " + nginxImage)
  1059. framework.RunKubectlOrDie("run", name, "--image="+nginxImage, nsFlag)
  1060. By("verifying the pod controlled by " + name + " gets created")
  1061. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": name}))
  1062. podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
  1063. if err != nil {
  1064. framework.Failf("Failed getting pod controlled by %s: %v", name, err)
  1065. }
  1066. pods := podlist.Items
  1067. if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
  1068. framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
  1069. framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
  1070. }
  1071. })
  1072. })
  1073. framework.KubeDescribe("Kubectl run rc", func() {
  1074. var nsFlag string
  1075. var rcName string
  1076. BeforeEach(func() {
  1077. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1078. rcName = "e2e-test-nginx-rc"
  1079. })
  1080. AfterEach(func() {
  1081. framework.RunKubectlOrDie("delete", "rc", rcName, nsFlag)
  1082. })
  1083. /*
  1084. Release : v1.9
  1085. Testname: Kubectl, run rc
  1086. Description: Command ‘kubectl run’ MUST create a running rc with default one replicas given a image using the option --image=’nginx’. The running replication controller SHOULD have one container and the container SHOULD be running the image specified in the ‘run’ command. Also there MUST be 1 pod controlled by this replica set running 1 container with the image specified. A ‘kubetctl logs’ command MUST return the logs from the container in the replication controller.
  1087. */
  1088. framework.ConformanceIt("should create an rc from an image ", func() {
  1089. By("running the image " + nginxImage)
  1090. framework.RunKubectlOrDie("run", rcName, "--image="+nginxImage, "--generator=run/v1", nsFlag)
  1091. By("verifying the rc " + rcName + " was created")
  1092. rc, err := c.CoreV1().ReplicationControllers(ns).Get(rcName, metav1.GetOptions{})
  1093. if err != nil {
  1094. framework.Failf("Failed getting rc %s: %v", rcName, err)
  1095. }
  1096. containers := rc.Spec.Template.Spec.Containers
  1097. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  1098. framework.Failf("Failed creating rc %s for 1 pod with expected image %s", rcName, nginxImage)
  1099. }
  1100. By("verifying the pod controlled by rc " + rcName + " was created")
  1101. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": rcName}))
  1102. podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
  1103. if err != nil {
  1104. framework.Failf("Failed getting pod controlled by rc %s: %v", rcName, err)
  1105. }
  1106. pods := podlist.Items
  1107. if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
  1108. framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
  1109. framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
  1110. }
  1111. By("confirm that you can get logs from an rc")
  1112. podNames := []string{}
  1113. for _, pod := range pods {
  1114. podNames = append(podNames, pod.Name)
  1115. }
  1116. if !framework.CheckPodsRunningReady(c, ns, podNames, framework.PodStartTimeout) {
  1117. framework.Failf("Pods for rc %s were not ready", rcName)
  1118. }
  1119. _, err = framework.RunKubectl("logs", "rc/"+rcName, nsFlag)
  1120. // a non-nil error is fine as long as we actually found a pod.
  1121. if err != nil && !strings.Contains(err.Error(), " in pod ") {
  1122. framework.Failf("Failed getting logs by rc %s: %v", rcName, err)
  1123. }
  1124. })
  1125. })
  1126. framework.KubeDescribe("Kubectl rolling-update", func() {
  1127. var nsFlag string
  1128. var rcName string
  1129. var c clientset.Interface
  1130. BeforeEach(func() {
  1131. c = f.ClientSet
  1132. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1133. rcName = "e2e-test-nginx-rc"
  1134. })
  1135. AfterEach(func() {
  1136. framework.RunKubectlOrDie("delete", "rc", rcName, nsFlag)
  1137. })
  1138. /*
  1139. Release : v1.9
  1140. Testname: Kubectl, rolling update
  1141. Description: Command ‘kubectl rolling-update’ MUST replace the specified replication controller with a new replication controller by updating one pod at a time to use the new Pod spec.
  1142. */
  1143. framework.ConformanceIt("should support rolling-update to same image ", func() {
  1144. By("running the image " + nginxImage)
  1145. framework.RunKubectlOrDie("run", rcName, "--image="+nginxImage, "--generator=run/v1", nsFlag)
  1146. By("verifying the rc " + rcName + " was created")
  1147. rc, err := c.CoreV1().ReplicationControllers(ns).Get(rcName, metav1.GetOptions{})
  1148. if err != nil {
  1149. framework.Failf("Failed getting rc %s: %v", rcName, err)
  1150. }
  1151. containers := rc.Spec.Template.Spec.Containers
  1152. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  1153. framework.Failf("Failed creating rc %s for 1 pod with expected image %s", rcName, nginxImage)
  1154. }
  1155. framework.WaitForRCToStabilize(c, ns, rcName, framework.PodStartTimeout)
  1156. By("rolling-update to same image controller")
  1157. runKubectlRetryOrDie("rolling-update", rcName, "--update-period=1s", "--image="+nginxImage, "--image-pull-policy="+string(v1.PullIfNotPresent), nsFlag)
  1158. framework.ValidateController(c, nginxImage, 1, rcName, "run="+rcName, noOpValidatorFn, ns)
  1159. })
  1160. })
  1161. framework.KubeDescribe("Kubectl run deployment", func() {
  1162. var nsFlag string
  1163. var dName string
  1164. BeforeEach(func() {
  1165. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1166. dName = "e2e-test-nginx-deployment"
  1167. })
  1168. AfterEach(func() {
  1169. err := wait.Poll(framework.Poll, 2*time.Minute, func() (bool, error) {
  1170. out, err := framework.RunKubectl("delete", "deployment", dName, nsFlag)
  1171. if err != nil {
  1172. if strings.Contains(err.Error(), "could not find default credentials") {
  1173. err = nil
  1174. }
  1175. return false, fmt.Errorf("kubectl delete failed output: %s, err: %v", out, err)
  1176. }
  1177. return true, nil
  1178. })
  1179. Expect(err).NotTo(HaveOccurred())
  1180. })
  1181. /*
  1182. Release : v1.9
  1183. Testname: Kubectl, run deployment
  1184. Description: Command ‘kubectl run’ MUST create a job, with --generator=deployment, when a image name is specified in the run command. After the run command there SHOULD be a deployment that should exist with one container running the specified image. Also there SHOULD be a Pod that is controlled by this deployment, with a container running the specified image.
  1185. */
  1186. framework.ConformanceIt("should create a deployment from an image ", func() {
  1187. By("running the image " + nginxImage)
  1188. framework.RunKubectlOrDie("run", dName, "--image="+nginxImage, "--generator=deployment/v1beta1", nsFlag)
  1189. By("verifying the deployment " + dName + " was created")
  1190. d, err := c.ExtensionsV1beta1().Deployments(ns).Get(dName, metav1.GetOptions{})
  1191. if err != nil {
  1192. framework.Failf("Failed getting deployment %s: %v", dName, err)
  1193. }
  1194. containers := d.Spec.Template.Spec.Containers
  1195. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  1196. framework.Failf("Failed creating deployment %s for 1 pod with expected image %s", dName, nginxImage)
  1197. }
  1198. By("verifying the pod controlled by deployment " + dName + " was created")
  1199. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": dName}))
  1200. podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
  1201. if err != nil {
  1202. framework.Failf("Failed getting pod controlled by deployment %s: %v", dName, err)
  1203. }
  1204. pods := podlist.Items
  1205. if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
  1206. framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
  1207. framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
  1208. }
  1209. })
  1210. })
  1211. framework.KubeDescribe("Kubectl run job", func() {
  1212. var nsFlag string
  1213. var jobName string
  1214. BeforeEach(func() {
  1215. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1216. jobName = "e2e-test-nginx-job"
  1217. })
  1218. AfterEach(func() {
  1219. framework.RunKubectlOrDie("delete", "jobs", jobName, nsFlag)
  1220. })
  1221. /*
  1222. Release : v1.9
  1223. Testname: Kubectl, run job
  1224. Description: Command ‘kubectl run’ MUST create a deployment, with --generator=job, when a image name is specified in the run command. After the run command there SHOULD be a job that should exist with one container running the specified image. Also there SHOULD be a restart policy on the job spec that SHOULD match the command line.
  1225. */
  1226. framework.ConformanceIt("should create a job from an image when restart is OnFailure ", func() {
  1227. By("running the image " + nginxImage)
  1228. framework.RunKubectlOrDie("run", jobName, "--restart=OnFailure", "--generator=job/v1", "--image="+nginxImage, nsFlag)
  1229. By("verifying the job " + jobName + " was created")
  1230. job, err := c.BatchV1().Jobs(ns).Get(jobName, metav1.GetOptions{})
  1231. if err != nil {
  1232. framework.Failf("Failed getting job %s: %v", jobName, err)
  1233. }
  1234. containers := job.Spec.Template.Spec.Containers
  1235. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  1236. framework.Failf("Failed creating job %s for 1 pod with expected image %s: %#v", jobName, nginxImage, containers)
  1237. }
  1238. if job.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure {
  1239. framework.Failf("Failed creating a job with correct restart policy for --restart=OnFailure")
  1240. }
  1241. })
  1242. })
  1243. framework.KubeDescribe("Kubectl run CronJob", func() {
  1244. var nsFlag string
  1245. var cjName string
  1246. BeforeEach(func() {
  1247. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1248. cjName = "e2e-test-echo-cronjob-beta"
  1249. })
  1250. AfterEach(func() {
  1251. framework.RunKubectlOrDie("delete", "cronjobs", cjName, nsFlag)
  1252. })
  1253. It("should create a CronJob", func() {
  1254. framework.SkipIfMissingResource(f.DynamicClient, CronJobGroupVersionResourceBeta, f.Namespace.Name)
  1255. schedule := "*/5 * * * ?"
  1256. framework.RunKubectlOrDie("run", cjName, "--restart=OnFailure", "--generator=cronjob/v1beta1",
  1257. "--schedule="+schedule, "--image="+busyboxImage, nsFlag)
  1258. By("verifying the CronJob " + cjName + " was created")
  1259. cj, err := c.BatchV1beta1().CronJobs(ns).Get(cjName, metav1.GetOptions{})
  1260. if err != nil {
  1261. framework.Failf("Failed getting CronJob %s: %v", cjName, err)
  1262. }
  1263. if cj.Spec.Schedule != schedule {
  1264. framework.Failf("Failed creating a CronJob with correct schedule %s", schedule)
  1265. }
  1266. containers := cj.Spec.JobTemplate.Spec.Template.Spec.Containers
  1267. if containers == nil || len(containers) != 1 || containers[0].Image != busyboxImage {
  1268. framework.Failf("Failed creating CronJob %s for 1 pod with expected image %s: %#v", cjName, busyboxImage, containers)
  1269. }
  1270. if cj.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure {
  1271. framework.Failf("Failed creating a CronJob with correct restart policy for --restart=OnFailure")
  1272. }
  1273. })
  1274. })
  1275. framework.KubeDescribe("Kubectl run pod", func() {
  1276. var nsFlag string
  1277. var podName string
  1278. BeforeEach(func() {
  1279. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1280. podName = "e2e-test-nginx-pod"
  1281. })
  1282. AfterEach(func() {
  1283. framework.RunKubectlOrDie("delete", "pods", podName, nsFlag)
  1284. })
  1285. /*
  1286. Release : v1.9
  1287. Testname: Kubectl, run pod
  1288. Description: Command ‘kubectl run’ MUST create a pod, with --generator=run-pod, when a image name is specified in the run command. After the run command there SHOULD be a pod that should exist with one container running the specified image.
  1289. */
  1290. framework.ConformanceIt("should create a pod from an image when restart is Never ", func() {
  1291. By("running the image " + nginxImage)
  1292. framework.RunKubectlOrDie("run", podName, "--restart=Never", "--generator=run-pod/v1", "--image="+nginxImage, nsFlag)
  1293. By("verifying the pod " + podName + " was created")
  1294. pod, err := c.CoreV1().Pods(ns).Get(podName, metav1.GetOptions{})
  1295. if err != nil {
  1296. framework.Failf("Failed getting pod %s: %v", podName, err)
  1297. }
  1298. containers := pod.Spec.Containers
  1299. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  1300. framework.Failf("Failed creating pod %s with expected image %s", podName, nginxImage)
  1301. }
  1302. if pod.Spec.RestartPolicy != v1.RestartPolicyNever {
  1303. framework.Failf("Failed creating a pod with correct restart policy for --restart=Never")
  1304. }
  1305. })
  1306. })
  1307. framework.KubeDescribe("Kubectl replace", func() {
  1308. var nsFlag string
  1309. var podName string
  1310. BeforeEach(func() {
  1311. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  1312. podName = "e2e-test-nginx-pod"
  1313. })
  1314. AfterEach(func() {
  1315. framework.RunKubectlOrDie("delete", "pods", podName, nsFlag)
  1316. })
  1317. /*
  1318. Release : v1.9
  1319. Testname: Kubectl, replace
  1320. Description: Command ‘kubectl replace’ on a existing Pod with a new spec MUST update the image of the container running in the Pod. A -f option to ‘kubectl replace’ SHOULD force to re-create the resource. The new Pod SHOULD have the container with new change to the image.
  1321. */
  1322. framework.ConformanceIt("should update a single-container pod's image ", func() {
  1323. By("running the image " + nginxImage)
  1324. framework.RunKubectlOrDie("run", podName, "--generator=run-pod/v1", "--image="+nginxImage, "--labels=run="+podName, nsFlag)
  1325. By("verifying the pod " + podName + " is running")
  1326. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": podName}))
  1327. err := testutils.WaitForPodsWithLabelRunning(c, ns, label)
  1328. if err != nil {
  1329. framework.Failf("Failed getting pod %s: %v", podName, err)
  1330. }
  1331. By("verifying the pod " + podName + " was created")
  1332. podJson := framework.RunKubectlOrDie("get", "pod", podName, nsFlag, "-o", "json")
  1333. if !strings.Contains(podJson, podName) {
  1334. framework.Failf("Failed to find pod %s in [%s]", podName, podJson)
  1335. }
  1336. By("replace the image in the pod")
  1337. podJson = strings.Replace(podJson, nginxImage, busyboxImage, 1)
  1338. framework.RunKubectlOrDieInput(podJson, "replace", "-f", "-", nsFlag)
  1339. By("verifying the pod " + podName + " has the right image " + busyboxImage)
  1340. pod, err := c.CoreV1().Pods(ns).Get(podName, metav1.GetOptions{})
  1341. if err != nil {
  1342. framework.Failf("Failed getting deployment %s: %v", podName, err)
  1343. }
  1344. containers := pod.Spec.Containers
  1345. if containers == nil || len(containers) != 1 || containers[0].Image != busyboxImage {
  1346. framework.Failf("Failed creating pod with expected image %s", busyboxImage)
  1347. }
  1348. })
  1349. })
  1350. framework.KubeDescribe("Kubectl run --rm job", func() {
  1351. jobName := "e2e-test-rm-busybox-job"
  1352. /*
  1353. Release : v1.9
  1354. Testname: Kubectl, run job with --rm
  1355. Description: Start a job with a Pod using ‘kubectl run’ but specify --rm=true. Wait for the Pod to start running by verifying that there is output as expected. Now verify that the job has exited and cannot be found. With --rm=true option the job MUST start by running the image specified and then get deleted itself.
  1356. */
  1357. framework.ConformanceIt("should create a job from an image, then delete the job ", func() {
  1358. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1359. By("executing a command with run --rm and attach with stdin")
  1360. t := time.NewTimer(runJobTimeout)
  1361. defer t.Stop()
  1362. runOutput := framework.NewKubectlCommand(nsFlag, "run", jobName, "--image="+busyboxImage, "--rm=true", "--generator=job/v1", "--restart=OnFailure", "--attach=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
  1363. WithStdinData("abcd1234").
  1364. WithTimeout(t.C).
  1365. ExecOrDie()
  1366. Expect(runOutput).To(ContainSubstring("abcd1234"))
  1367. Expect(runOutput).To(ContainSubstring("stdin closed"))
  1368. err := framework.WaitForJobGone(c, ns, jobName, wait.ForeverTestTimeout)
  1369. Expect(err).NotTo(HaveOccurred())
  1370. By("verifying the job " + jobName + " was deleted")
  1371. _, err = c.BatchV1().Jobs(ns).Get(jobName, metav1.GetOptions{})
  1372. Expect(err).To(HaveOccurred())
  1373. Expect(apierrs.IsNotFound(err)).To(BeTrue())
  1374. })
  1375. })
  1376. framework.KubeDescribe("Proxy server", func() {
  1377. // TODO: test proxy options (static, prefix, etc)
  1378. /*
  1379. Release : v1.9
  1380. Testname: Kubectl, proxy port zero
  1381. Description: Start a proxy server on port zero by running ‘kubectl proxy’ with --port=0. Call the proxy server by requesting api versions from unix socket. The proxy server MUST provide at least one version string.
  1382. */
  1383. framework.ConformanceIt("should support proxy with --port 0 ", func() {
  1384. By("starting the proxy server")
  1385. port, cmd, err := startProxyServer()
  1386. if cmd != nil {
  1387. defer framework.TryKill(cmd)
  1388. }
  1389. if err != nil {
  1390. framework.Failf("Failed to start proxy server: %v", err)
  1391. }
  1392. By("curling proxy /api/ output")
  1393. localAddr := fmt.Sprintf("http://localhost:%d/api/", port)
  1394. apiVersions, err := getAPIVersions(localAddr)
  1395. if err != nil {
  1396. framework.Failf("Expected at least one supported apiversion, got error %v", err)
  1397. }
  1398. if len(apiVersions.Versions) < 1 {
  1399. framework.Failf("Expected at least one supported apiversion, got %v", apiVersions)
  1400. }
  1401. })
  1402. /*
  1403. Release : v1.9
  1404. Testname: Kubectl, proxy socket
  1405. Description: Start a proxy server on by running ‘kubectl proxy’ with --unix-socket=<some path>. Call the proxy server by requesting api versions from http://locahost:0/api. The proxy server MUST provide atleast one version string
  1406. */
  1407. framework.ConformanceIt("should support --unix-socket=/path ", func() {
  1408. By("Starting the proxy")
  1409. tmpdir, err := ioutil.TempDir("", "kubectl-proxy-unix")
  1410. if err != nil {
  1411. framework.Failf("Failed to create temporary directory: %v", err)
  1412. }
  1413. path := filepath.Join(tmpdir, "test")
  1414. defer os.Remove(path)
  1415. defer os.Remove(tmpdir)
  1416. cmd := framework.KubectlCmd("proxy", fmt.Sprintf("--unix-socket=%s", path))
  1417. stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)
  1418. if err != nil {
  1419. framework.Failf("Failed to start kubectl command: %v", err)
  1420. }
  1421. defer stdout.Close()
  1422. defer stderr.Close()
  1423. defer framework.TryKill(cmd)
  1424. buf := make([]byte, 128)
  1425. if _, err = stdout.Read(buf); err != nil {
  1426. framework.Failf("Expected output from kubectl proxy: %v", err)
  1427. }
  1428. By("retrieving proxy /api/ output")
  1429. _, err = curlUnix("http://unused/api", path)
  1430. if err != nil {
  1431. framework.Failf("Failed get of /api at %s: %v", path, err)
  1432. }
  1433. })
  1434. })
  1435. // This test must run [Serial] because it modifies the node so it doesn't allow pods to execute on
  1436. // it, which will affect anything else running in parallel.
  1437. framework.KubeDescribe("Kubectl taint [Serial]", func() {
  1438. It("should update the taint on a node", func() {
  1439. testTaint := v1.Taint{
  1440. Key: fmt.Sprintf("kubernetes.io/e2e-taint-key-001-%s", string(uuid.NewUUID())),
  1441. Value: "testing-taint-value",
  1442. Effect: v1.TaintEffectNoSchedule,
  1443. }
  1444. nodeName := scheduling.GetNodeThatCanRunPod(f)
  1445. By("adding the taint " + testTaint.ToString() + " to a node")
  1446. runKubectlRetryOrDie("taint", "nodes", nodeName, testTaint.ToString())
  1447. defer framework.RemoveTaintOffNode(f.ClientSet, nodeName, testTaint)
  1448. By("verifying the node has the taint " + testTaint.ToString())
  1449. output := runKubectlRetryOrDie("describe", "node", nodeName)
  1450. requiredStrings := [][]string{
  1451. {"Name:", nodeName},
  1452. {"Taints:"},
  1453. {testTaint.ToString()},
  1454. }
  1455. checkOutput(output, requiredStrings)
  1456. By("removing the taint " + testTaint.ToString() + " of a node")
  1457. runKubectlRetryOrDie("taint", "nodes", nodeName, testTaint.Key+":"+string(testTaint.Effect)+"-")
  1458. By("verifying the node doesn't have the taint " + testTaint.Key)
  1459. output = runKubectlRetryOrDie("describe", "node", nodeName)
  1460. if strings.Contains(output, testTaint.Key) {
  1461. framework.Failf("Failed removing taint " + testTaint.Key + " of the node " + nodeName)
  1462. }
  1463. })
  1464. It("should remove all the taints with the same key off a node", func() {
  1465. testTaint := v1.Taint{
  1466. Key: fmt.Sprintf("kubernetes.io/e2e-taint-key-002-%s", string(uuid.NewUUID())),
  1467. Value: "testing-taint-value",
  1468. Effect: v1.TaintEffectNoSchedule,
  1469. }
  1470. nodeName := scheduling.GetNodeThatCanRunPod(f)
  1471. By("adding the taint " + testTaint.ToString() + " to a node")
  1472. runKubectlRetryOrDie("taint", "nodes", nodeName, testTaint.ToString())
  1473. defer framework.RemoveTaintOffNode(f.ClientSet, nodeName, testTaint)
  1474. By("verifying the node has the taint " + testTaint.ToString())
  1475. output := runKubectlRetryOrDie("describe", "node", nodeName)
  1476. requiredStrings := [][]string{
  1477. {"Name:", nodeName},
  1478. {"Taints:"},
  1479. {testTaint.ToString()},
  1480. }
  1481. checkOutput(output, requiredStrings)
  1482. newTestTaint := v1.Taint{
  1483. Key: testTaint.Key,
  1484. Value: "another-testing-taint-value",
  1485. Effect: v1.TaintEffectPreferNoSchedule,
  1486. }
  1487. By("adding another taint " + newTestTaint.ToString() + " to the node")
  1488. runKubectlRetryOrDie("taint", "nodes", nodeName, newTestTaint.ToString())
  1489. defer framework.RemoveTaintOffNode(f.ClientSet, nodeName, newTestTaint)
  1490. By("verifying the node has the taint " + newTestTaint.ToString())
  1491. output = runKubectlRetryOrDie("describe", "node", nodeName)
  1492. requiredStrings = [][]string{
  1493. {"Name:", nodeName},
  1494. {"Taints:"},
  1495. {newTestTaint.ToString()},
  1496. }
  1497. checkOutput(output, requiredStrings)
  1498. noExecuteTaint := v1.Taint{
  1499. Key: testTaint.Key,
  1500. Value: "testing-taint-value-no-execute",
  1501. Effect: v1.TaintEffectNoExecute,
  1502. }
  1503. By("adding NoExecute taint " + noExecuteTaint.ToString() + " to the node")
  1504. runKubectlRetryOrDie("taint", "nodes", nodeName, noExecuteTaint.ToString())
  1505. defer framework.RemoveTaintOffNode(f.ClientSet, nodeName, noExecuteTaint)
  1506. By("verifying the node has the taint " + noExecuteTaint.ToString())
  1507. output = runKubectlRetryOrDie("describe", "node", nodeName)
  1508. requiredStrings = [][]string{
  1509. {"Name:", nodeName},
  1510. {"Taints:"},
  1511. {noExecuteTaint.ToString()},
  1512. }
  1513. checkOutput(output, requiredStrings)
  1514. By("removing all taints that have the same key " + testTaint.Key + " of the node")
  1515. runKubectlRetryOrDie("taint", "nodes", nodeName, testTaint.Key+"-")
  1516. By("verifying the node doesn't have the taints that have the same key " + testTaint.Key)
  1517. output = runKubectlRetryOrDie("describe", "node", nodeName)
  1518. if strings.Contains(output, testTaint.Key) {
  1519. framework.Failf("Failed removing taints " + testTaint.Key + " of the node " + nodeName)
  1520. }
  1521. })
  1522. })
  1523. framework.KubeDescribe("Kubectl create quota", func() {
  1524. It("should create a quota without scopes", func() {
  1525. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1526. quotaName := "million"
  1527. By("calling kubectl quota")
  1528. framework.RunKubectlOrDie("create", "quota", quotaName, "--hard=pods=1000000,services=1000000", nsFlag)
  1529. By("verifying that the quota was created")
  1530. quota, err := c.CoreV1().ResourceQuotas(ns).Get(quotaName, metav1.GetOptions{})
  1531. if err != nil {
  1532. framework.Failf("Failed getting quota %s: %v", quotaName, err)
  1533. }
  1534. if len(quota.Spec.Scopes) != 0 {
  1535. framework.Failf("Expected empty scopes, got %v", quota.Spec.Scopes)
  1536. }
  1537. if len(quota.Spec.Hard) != 2 {
  1538. framework.Failf("Expected two resources, got %v", quota.Spec.Hard)
  1539. }
  1540. r, found := quota.Spec.Hard[v1.ResourcePods]
  1541. if expected := resource.MustParse("1000000"); !found || (&r).Cmp(expected) != 0 {
  1542. framework.Failf("Expected pods=1000000, got %v", r)
  1543. }
  1544. r, found = quota.Spec.Hard[v1.ResourceServices]
  1545. if expected := resource.MustParse("1000000"); !found || (&r).Cmp(expected) != 0 {
  1546. framework.Failf("Expected services=1000000, got %v", r)
  1547. }
  1548. })
  1549. It("should create a quota with scopes", func() {
  1550. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1551. quotaName := "scopes"
  1552. By("calling kubectl quota")
  1553. framework.RunKubectlOrDie("create", "quota", quotaName, "--hard=pods=1000000", "--scopes=BestEffort,NotTerminating", nsFlag)
  1554. By("verifying that the quota was created")
  1555. quota, err := c.CoreV1().ResourceQuotas(ns).Get(quotaName, metav1.GetOptions{})
  1556. if err != nil {
  1557. framework.Failf("Failed getting quota %s: %v", quotaName, err)
  1558. }
  1559. if len(quota.Spec.Scopes) != 2 {
  1560. framework.Failf("Expected two scopes, got %v", quota.Spec.Scopes)
  1561. }
  1562. scopes := make(map[v1.ResourceQuotaScope]struct{})
  1563. for _, scope := range quota.Spec.Scopes {
  1564. scopes[scope] = struct{}{}
  1565. }
  1566. if _, found := scopes[v1.ResourceQuotaScopeBestEffort]; !found {
  1567. framework.Failf("Expected BestEffort scope, got %v", quota.Spec.Scopes)
  1568. }
  1569. if _, found := scopes[v1.ResourceQuotaScopeNotTerminating]; !found {
  1570. framework.Failf("Expected NotTerminating scope, got %v", quota.Spec.Scopes)
  1571. }
  1572. })
  1573. It("should reject quota with invalid scopes", func() {
  1574. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1575. quotaName := "scopes"
  1576. By("calling kubectl quota")
  1577. out, err := framework.RunKubectl("create", "quota", quotaName, "--hard=hard=pods=1000000", "--scopes=Foo", nsFlag)
  1578. if err == nil {
  1579. framework.Failf("Expected kubectl to fail, but it succeeded: %s", out)
  1580. }
  1581. })
  1582. })
  1583. })
  1584. // Checks whether the output split by line contains the required elements.
  1585. func checkOutputReturnError(output string, required [][]string) error {
  1586. outputLines := strings.Split(output, "\n")
  1587. currentLine := 0
  1588. for _, requirement := range required {
  1589. for currentLine < len(outputLines) && !strings.Contains(outputLines[currentLine], requirement[0]) {
  1590. currentLine++
  1591. }
  1592. if currentLine == len(outputLines) {
  1593. return fmt.Errorf("failed to find %s in %s", requirement[0], output)
  1594. }
  1595. for _, item := range requirement[1:] {
  1596. if !strings.Contains(outputLines[currentLine], item) {
  1597. return fmt.Errorf("failed to find %s in %s", item, outputLines[currentLine])
  1598. }
  1599. }
  1600. }
  1601. return nil
  1602. }
  1603. func checkOutput(output string, required [][]string) {
  1604. err := checkOutputReturnError(output, required)
  1605. if err != nil {
  1606. framework.Failf("%v", err)
  1607. }
  1608. }
  1609. func checkKubectlOutputWithRetry(required [][]string, args ...string) {
  1610. var pollErr error
  1611. wait.PollImmediate(time.Second, time.Minute, func() (bool, error) {
  1612. output := framework.RunKubectlOrDie(args...)
  1613. err := checkOutputReturnError(output, required)
  1614. if err != nil {
  1615. pollErr = err
  1616. return false, nil
  1617. }
  1618. pollErr = nil
  1619. return true, nil
  1620. })
  1621. if pollErr != nil {
  1622. framework.Failf("%v", pollErr)
  1623. }
  1624. return
  1625. }
  1626. func getAPIVersions(apiEndpoint string) (*metav1.APIVersions, error) {
  1627. body, err := curl(apiEndpoint)
  1628. if err != nil {
  1629. return nil, fmt.Errorf("Failed http.Get of %s: %v", apiEndpoint, err)
  1630. }
  1631. var apiVersions metav1.APIVersions
  1632. if err := json.Unmarshal([]byte(body), &apiVersions); err != nil {
  1633. return nil, fmt.Errorf("Failed to parse /api output %s: %v", body, err)
  1634. }
  1635. return &apiVersions, nil
  1636. }
  1637. func startProxyServer() (int, *exec.Cmd, error) {
  1638. // Specifying port 0 indicates we want the os to pick a random port.
  1639. cmd := framework.KubectlCmd("proxy", "-p", "0", "--disable-filter")
  1640. stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)
  1641. if err != nil {
  1642. return -1, nil, err
  1643. }
  1644. defer stdout.Close()
  1645. defer stderr.Close()
  1646. buf := make([]byte, 128)
  1647. var n int
  1648. if n, err = stdout.Read(buf); err != nil {
  1649. return -1, cmd, fmt.Errorf("Failed to read from kubectl proxy stdout: %v", err)
  1650. }
  1651. output := string(buf[:n])
  1652. match := proxyRegexp.FindStringSubmatch(output)
  1653. if len(match) == 2 {
  1654. if port, err := strconv.Atoi(match[1]); err == nil {
  1655. return port, cmd, nil
  1656. }
  1657. }
  1658. return -1, cmd, fmt.Errorf("Failed to parse port from proxy stdout: %s", output)
  1659. }
  1660. func curlUnix(url string, path string) (string, error) {
  1661. dial := func(ctx context.Context, proto, addr string) (net.Conn, error) {
  1662. var d net.Dialer
  1663. return d.DialContext(ctx, "unix", path)
  1664. }
  1665. transport := utilnet.SetTransportDefaults(&http.Transport{
  1666. DialContext: dial,
  1667. })
  1668. return curlTransport(url, transport)
  1669. }
  1670. func curlTransport(url string, transport *http.Transport) (string, error) {
  1671. client := &http.Client{Transport: transport}
  1672. resp, err := client.Get(url)
  1673. if err != nil {
  1674. return "", err
  1675. }
  1676. defer resp.Body.Close()
  1677. body, err := ioutil.ReadAll(resp.Body)
  1678. if err != nil {
  1679. return "", err
  1680. }
  1681. return string(body[:]), nil
  1682. }
  1683. func curl(url string) (string, error) {
  1684. return curlTransport(url, utilnet.SetTransportDefaults(&http.Transport{}))
  1685. }
  1686. func validateGuestbookApp(c clientset.Interface, ns string) {
  1687. framework.Logf("Waiting for all frontend pods to be Running.")
  1688. label := labels.SelectorFromSet(labels.Set(map[string]string{"tier": "frontend", "app": "guestbook"}))
  1689. err := testutils.WaitForPodsWithLabelRunning(c, ns, label)
  1690. Expect(err).NotTo(HaveOccurred())
  1691. framework.Logf("Waiting for frontend to serve content.")
  1692. if !waitForGuestbookResponse(c, "get", "", `{"data": ""}`, guestbookStartupTimeout, ns) {
  1693. framework.Failf("Frontend service did not start serving content in %v seconds.", guestbookStartupTimeout.Seconds())
  1694. }
  1695. framework.Logf("Trying to add a new entry to the guestbook.")
  1696. if !waitForGuestbookResponse(c, "set", "TestEntry", `{"message": "Updated"}`, guestbookResponseTimeout, ns) {
  1697. framework.Failf("Cannot added new entry in %v seconds.", guestbookResponseTimeout.Seconds())
  1698. }
  1699. framework.Logf("Verifying that added entry can be retrieved.")
  1700. if !waitForGuestbookResponse(c, "get", "", `{"data": "TestEntry"}`, guestbookResponseTimeout, ns) {
  1701. framework.Failf("Entry to guestbook wasn't correctly added in %v seconds.", guestbookResponseTimeout.Seconds())
  1702. }
  1703. }
  1704. // Returns whether received expected response from guestbook on time.
  1705. func waitForGuestbookResponse(c clientset.Interface, cmd, arg, expectedResponse string, timeout time.Duration, ns string) bool {
  1706. for start := time.Now(); time.Since(start) < timeout; time.Sleep(5 * time.Second) {
  1707. res, err := makeRequestToGuestbook(c, cmd, arg, ns)
  1708. if err == nil && res == expectedResponse {
  1709. return true
  1710. }
  1711. framework.Logf("Failed to get response from guestbook. err: %v, response: %s", err, res)
  1712. }
  1713. return false
  1714. }
  1715. func makeRequestToGuestbook(c clientset.Interface, cmd, value string, ns string) (string, error) {
  1716. proxyRequest, errProxy := framework.GetServicesProxyRequest(c, c.CoreV1().RESTClient().Get())
  1717. if errProxy != nil {
  1718. return "", errProxy
  1719. }
  1720. ctx, cancel := context.WithTimeout(context.Background(), framework.SingleCallTimeout)
  1721. defer cancel()
  1722. result, err := proxyRequest.Namespace(ns).
  1723. Context(ctx).
  1724. Name("frontend").
  1725. Suffix("/guestbook.php").
  1726. Param("cmd", cmd).
  1727. Param("key", "messages").
  1728. Param("value", value).
  1729. Do().
  1730. Raw()
  1731. return string(result), err
  1732. }
  1733. type updateDemoData struct {
  1734. Image string
  1735. }
  1736. const applyTestLabel = "kubectl.kubernetes.io/apply-test"
  1737. func readBytesFromFile(filename string) []byte {
  1738. file, err := os.Open(filename)
  1739. if err != nil {
  1740. framework.Failf(err.Error())
  1741. }
  1742. defer file.Close()
  1743. data, err := ioutil.ReadAll(file)
  1744. if err != nil {
  1745. framework.Failf(err.Error())
  1746. }
  1747. return data
  1748. }
  1749. func readReplicationControllerFromString(contents string) *v1.ReplicationController {
  1750. rc := v1.ReplicationController{}
  1751. if err := yaml.Unmarshal([]byte(contents), &rc); err != nil {
  1752. framework.Failf(err.Error())
  1753. }
  1754. return &rc
  1755. }
  1756. func modifyReplicationControllerConfiguration(contents string) io.Reader {
  1757. rc := readReplicationControllerFromString(contents)
  1758. rc.Labels[applyTestLabel] = "ADDED"
  1759. rc.Spec.Selector[applyTestLabel] = "ADDED"
  1760. rc.Spec.Template.Labels[applyTestLabel] = "ADDED"
  1761. data, err := json.Marshal(rc)
  1762. if err != nil {
  1763. framework.Failf("json marshal failed: %s\n", err)
  1764. }
  1765. return bytes.NewReader(data)
  1766. }
  1767. func forEachReplicationController(c clientset.Interface, ns, selectorKey, selectorValue string, fn func(v1.ReplicationController)) {
  1768. var rcs *v1.ReplicationControllerList
  1769. var err error
  1770. for t := time.Now(); time.Since(t) < framework.PodListTimeout; time.Sleep(framework.Poll) {
  1771. label := labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue}))
  1772. options := metav1.ListOptions{LabelSelector: label.String()}
  1773. rcs, err = c.CoreV1().ReplicationControllers(ns).List(options)
  1774. Expect(err).NotTo(HaveOccurred())
  1775. if len(rcs.Items) > 0 {
  1776. break
  1777. }
  1778. }
  1779. if rcs == nil || len(rcs.Items) == 0 {
  1780. framework.Failf("No replication controllers found")
  1781. }
  1782. for _, rc := range rcs.Items {
  1783. fn(rc)
  1784. }
  1785. }
  1786. func validateReplicationControllerConfiguration(rc v1.ReplicationController) {
  1787. if rc.Name == "redis-master" {
  1788. if _, ok := rc.Annotations[v1.LastAppliedConfigAnnotation]; !ok {
  1789. framework.Failf("Annotation not found in modified configuration:\n%v\n", rc)
  1790. }
  1791. if value, ok := rc.Labels[applyTestLabel]; !ok || value != "ADDED" {
  1792. framework.Failf("Added label %s not found in modified configuration:\n%v\n", applyTestLabel, rc)
  1793. }
  1794. }
  1795. }
  1796. // getUDData creates a validator function based on the input string (i.e. kitten.jpg).
  1797. // For example, if you send "kitten.jpg", this function verifies that the image jpg = kitten.jpg
  1798. // in the container's json field.
  1799. func getUDData(jpgExpected string, ns string) func(clientset.Interface, string) error {
  1800. // getUDData validates data.json in the update-demo (returns nil if data is ok).
  1801. return func(c clientset.Interface, podID string) error {
  1802. framework.Logf("validating pod %s", podID)
  1803. ctx, cancel := context.WithTimeout(context.Background(), framework.SingleCallTimeout)
  1804. defer cancel()
  1805. body, err := c.CoreV1().RESTClient().Get().
  1806. Namespace(ns).
  1807. Resource("pods").
  1808. SubResource("proxy").
  1809. Name(podID).
  1810. Suffix("data.json").
  1811. Do().
  1812. Raw()
  1813. if err != nil {
  1814. if ctx.Err() != nil {
  1815. framework.Failf("Failed to retrieve data from container: %v", err)
  1816. }
  1817. return err
  1818. }
  1819. framework.Logf("got data: %s", body)
  1820. var data updateDemoData
  1821. if err := json.Unmarshal(body, &data); err != nil {
  1822. return err
  1823. }
  1824. framework.Logf("Unmarshalled json jpg/img => %s , expecting %s .", data, jpgExpected)
  1825. if strings.Contains(data.Image, jpgExpected) {
  1826. return nil
  1827. } else {
  1828. return fmt.Errorf("data served up in container is inaccurate, %s didn't contain %s", data, jpgExpected)
  1829. }
  1830. }
  1831. }
  1832. func noOpValidatorFn(c clientset.Interface, podID string) error { return nil }
  1833. // newBlockingReader returns a reader that allows reading the given string,
  1834. // then blocks until Close() is called on the returned closer.
  1835. //
  1836. // We're explicitly returning the reader and closer separately, because
  1837. // the closer needs to be the *os.File we get from os.Pipe(). This is required
  1838. // so the exec of kubectl can pass the underlying file descriptor to the exec
  1839. // syscall, instead of creating another os.Pipe and blocking on the io.Copy
  1840. // between the source (e.g. stdin) and the write half of the pipe.
  1841. func newBlockingReader(s string) (io.Reader, io.Closer, error) {
  1842. r, w, err := os.Pipe()
  1843. if err != nil {
  1844. return nil, nil, err
  1845. }
  1846. w.Write([]byte(s))
  1847. return r, w, nil
  1848. }
  1849. // newStreamingUpload creates a new http.Request that will stream POST
  1850. // a file to a URI.
  1851. func newStreamingUpload(filePath string) (*io.PipeReader, *multipart.Writer, error) {
  1852. file, err := os.Open(filePath)
  1853. if err != nil {
  1854. return nil, nil, err
  1855. }
  1856. defer file.Close()
  1857. r, w := io.Pipe()
  1858. postBodyWriter := multipart.NewWriter(w)
  1859. go streamingUpload(file, filepath.Base(filePath), postBodyWriter, w)
  1860. return r, postBodyWriter, err
  1861. }
  1862. // streamingUpload streams a file via a pipe through a multipart.Writer.
  1863. // Generally one should use newStreamingUpload instead of calling this directly.
  1864. func streamingUpload(file *os.File, fileName string, postBodyWriter *multipart.Writer, w *io.PipeWriter) {
  1865. defer GinkgoRecover()
  1866. defer file.Close()
  1867. defer w.Close()
  1868. // Set up the form file
  1869. fileWriter, err := postBodyWriter.CreateFormFile("file", fileName)
  1870. if err != nil {
  1871. framework.Failf("Unable to to write file at %s to buffer. Error: %s", fileName, err)
  1872. }
  1873. // Copy kubectl binary into the file writer
  1874. if _, err := io.Copy(fileWriter, file); err != nil {
  1875. framework.Failf("Unable to to copy file at %s into the file writer. Error: %s", fileName, err)
  1876. }
  1877. // Nothing more should be written to this instance of the postBodyWriter
  1878. if err := postBodyWriter.Close(); err != nil {
  1879. framework.Failf("Unable to close the writer for file upload. Error: %s", err)
  1880. }
  1881. }
  1882. func startLocalProxy() (srv *httptest.Server, logs *bytes.Buffer) {
  1883. logs = &bytes.Buffer{}
  1884. p := goproxy.NewProxyHttpServer()
  1885. p.Verbose = true
  1886. p.Logger = log.New(logs, "", 0)
  1887. return httptest.NewServer(p), logs
  1888. }