kubectl.go 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package e2e
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "log"
  22. "mime/multipart"
  23. "net"
  24. "net/http"
  25. "net/http/httptest"
  26. "os"
  27. "os/exec"
  28. "path"
  29. "path/filepath"
  30. "regexp"
  31. "sort"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "github.com/elazarl/goproxy"
  36. "github.com/ghodss/yaml"
  37. "k8s.io/kubernetes/pkg/api"
  38. "k8s.io/kubernetes/pkg/api/annotations"
  39. apierrs "k8s.io/kubernetes/pkg/api/errors"
  40. "k8s.io/kubernetes/pkg/api/resource"
  41. "k8s.io/kubernetes/pkg/api/unversioned"
  42. client "k8s.io/kubernetes/pkg/client/unversioned"
  43. "k8s.io/kubernetes/pkg/controller"
  44. "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  45. "k8s.io/kubernetes/pkg/labels"
  46. "k8s.io/kubernetes/pkg/registry/generic/registry"
  47. uexec "k8s.io/kubernetes/pkg/util/exec"
  48. utilnet "k8s.io/kubernetes/pkg/util/net"
  49. "k8s.io/kubernetes/pkg/util/uuid"
  50. "k8s.io/kubernetes/pkg/util/wait"
  51. "k8s.io/kubernetes/pkg/version"
  52. "k8s.io/kubernetes/test/e2e/framework"
  53. . "github.com/onsi/ginkgo"
  54. . "github.com/onsi/gomega"
  55. )
  56. const (
  57. nautilusImage = "gcr.io/google_containers/update-demo:nautilus"
  58. kittenImage = "gcr.io/google_containers/update-demo:kitten"
  59. updateDemoSelector = "name=update-demo"
  60. updateDemoContainer = "update-demo"
  61. frontendSelector = "app=guestbook,tier=frontend"
  62. redisMasterSelector = "app=redis,role=master"
  63. redisSlaveSelector = "app=redis,role=slave"
  64. goproxyContainer = "goproxy"
  65. goproxyPodSelector = "name=goproxy"
  66. netexecContainer = "netexec"
  67. netexecPodSelector = "name=netexec"
  68. kubectlProxyPort = 8011
  69. guestbookStartupTimeout = 10 * time.Minute
  70. guestbookResponseTimeout = 3 * time.Minute
  71. simplePodSelector = "name=nginx"
  72. simplePodName = "nginx"
  73. nginxDefaultOutput = "Welcome to nginx!"
  74. simplePodPort = 80
  75. pausePodSelector = "name=pause"
  76. pausePodName = "pause"
  77. runJobTimeout = 5 * time.Minute
  78. busyboxImage = "gcr.io/google_containers/busybox:1.24"
  79. nginxImage = "gcr.io/google_containers/nginx-slim:0.7"
  80. kubeCtlManifestPath = "test/e2e/testing-manifests/kubectl"
  81. redisControllerFilename = "redis-master-controller.json"
  82. redisServiceFilename = "redis-master-service.json"
  83. )
  84. var (
  85. proxyRegexp = regexp.MustCompile("Starting to serve on 127.0.0.1:([0-9]+)")
  86. // Extended pod logging options were introduced in #13780 (v1.1.0) so we don't expect tests
  87. // that rely on extended pod logging options to work on clusters before that.
  88. //
  89. // TODO(ihmccreery): remove once we don't care about v1.0 anymore, (tentatively in v1.3).
  90. extendedPodLogFilterVersion = version.MustParse("v1.1.0")
  91. // NodePorts were made optional in #12831 (v1.1.0) so we don't expect tests that used to
  92. // require NodePorts but no longer include them to work on clusters before that.
  93. //
  94. // TODO(ihmccreery): remove once we don't care about v1.0 anymore, (tentatively in v1.3).
  95. nodePortsOptionalVersion = version.MustParse("v1.1.0")
  96. // Jobs were introduced in v1.1, so we don't expect tests that rely on jobs to work on
  97. // clusters before that.
  98. //
  99. // TODO(ihmccreery): remove once we don't care about v1.0 anymore, (tentatively in v1.3).
  100. jobsVersion = version.MustParse("v1.1.0")
  101. // Deployments were introduced by default in v1.2, so we don't expect tests that rely on
  102. // deployments to work on clusters before that.
  103. //
  104. // TODO(ihmccreery): remove once we don't care about v1.1 anymore, (tentatively in v1.4).
  105. deploymentsVersion = version.MustParse("v1.2.0-alpha.7.726")
  106. // Pod probe parameters were introduced in #15967 (v1.2) so we dont expect tests that use
  107. // these probe parameters to work on clusters before that.
  108. //
  109. // TODO(ihmccreery): remove once we don't care about v1.1 anymore, (tentatively in v1.4).
  110. podProbeParametersVersion = version.MustParse("v1.2.0-alpha.4")
  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", "-f", "-", nsArg)
  123. framework.AssertCleanup(ns, selectors...)
  124. }
  125. func readTestFileOrDie(file string) []byte {
  126. return framework.ReadOrDie(path.Join(kubeCtlManifestPath, file))
  127. }
  128. func runKubectlRetryOrDie(args ...string) string {
  129. var err error
  130. var output string
  131. for i := 0; i < 3; i++ {
  132. output, err = framework.RunKubectl(args...)
  133. if err == nil || !strings.Contains(err.Error(), registry.OptimisticLockErrorMsg) {
  134. break
  135. }
  136. time.Sleep(time.Second)
  137. }
  138. // Expect no errors to be present after retries are finished
  139. // Copied from framework #ExecOrDie
  140. framework.Logf("stdout: %q", output)
  141. Expect(err).NotTo(HaveOccurred())
  142. return output
  143. }
  144. var _ = framework.KubeDescribe("Kubectl client", func() {
  145. defer GinkgoRecover()
  146. f := framework.NewDefaultFramework("kubectl")
  147. // Reustable cluster state function. This won't be adversly affected by lazy initialization of framework.
  148. clusterState := func() *framework.ClusterVerification {
  149. return f.NewClusterVerification(
  150. framework.PodStateVerification{
  151. Selectors: map[string]string{"app": "redis"},
  152. ValidPhases: []api.PodPhase{api.PodRunning /*api.PodPending*/},
  153. })
  154. }
  155. forEachPod := func(podFunc func(p api.Pod)) {
  156. clusterState().ForEach(podFunc)
  157. }
  158. var c *client.Client
  159. var ns string
  160. BeforeEach(func() {
  161. c = f.Client
  162. ns = f.Namespace.Name
  163. })
  164. // Customized Wait / ForEach wrapper for this test. These demonstrate the
  165. // idiomatic way to wrap the ClusterVerification structs for syntactic sugar in large
  166. // test files.
  167. // Print debug info if atLeast Pods are not found before the timeout
  168. waitForOrFailWithDebug := func(atLeast int) {
  169. pods, err := clusterState().WaitFor(atLeast, framework.PodStartTimeout)
  170. if err != nil || len(pods) < atLeast {
  171. // TODO: Generalize integrating debug info into these tests so we always get debug info when we need it
  172. framework.DumpAllNamespaceInfo(c, ns)
  173. framework.Failf("Verified %v of %v pods , error : %v", len(pods), atLeast, err)
  174. }
  175. }
  176. framework.KubeDescribe("Update Demo", func() {
  177. var nautilus, kitten []byte
  178. BeforeEach(func() {
  179. updateDemoRoot := "test/fixtures/doc-yaml/user-guide/update-demo"
  180. nautilus = framework.ReadOrDie(filepath.Join(updateDemoRoot, "nautilus-rc.yaml"))
  181. kitten = framework.ReadOrDie(filepath.Join(updateDemoRoot, "kitten-rc.yaml"))
  182. })
  183. It("should create and stop a replication controller [Conformance]", func() {
  184. defer cleanupKubectlInputs(string(nautilus), ns, updateDemoSelector)
  185. By("creating a replication controller")
  186. framework.RunKubectlOrDieInput(string(nautilus[:]), "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  187. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  188. })
  189. It("should scale a replication controller [Conformance]", func() {
  190. defer cleanupKubectlInputs(string(nautilus[:]), ns, updateDemoSelector)
  191. By("creating a replication controller")
  192. framework.RunKubectlOrDieInput(string(nautilus[:]), "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  193. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  194. By("scaling down the replication controller")
  195. framework.RunKubectlOrDie("scale", "rc", "update-demo-nautilus", "--replicas=1", "--timeout=5m", fmt.Sprintf("--namespace=%v", ns))
  196. framework.ValidateController(c, nautilusImage, 1, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  197. By("scaling up the replication controller")
  198. framework.RunKubectlOrDie("scale", "rc", "update-demo-nautilus", "--replicas=2", "--timeout=5m", fmt.Sprintf("--namespace=%v", ns))
  199. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  200. })
  201. It("should do a rolling update of a replication controller [Conformance]", func() {
  202. By("creating the initial replication controller")
  203. framework.RunKubectlOrDieInput(string(nautilus[:]), "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  204. framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
  205. By("rolling-update to new replication controller")
  206. framework.RunKubectlOrDieInput(string(kitten[:]), "rolling-update", "update-demo-nautilus", "--update-period=1s", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  207. framework.ValidateController(c, kittenImage, 2, "update-demo", updateDemoSelector, getUDData("kitten.jpg", ns), ns)
  208. // Everything will hopefully be cleaned up when the namespace is deleted.
  209. })
  210. })
  211. framework.KubeDescribe("Guestbook application", func() {
  212. forEachGBFile := func(run func(s string)) {
  213. for _, gbAppFile := range []string{
  214. "examples/guestbook/frontend-deployment.yaml",
  215. "examples/guestbook/frontend-service.yaml",
  216. "examples/guestbook/redis-master-deployment.yaml",
  217. "examples/guestbook/redis-master-service.yaml",
  218. "examples/guestbook/redis-slave-deployment.yaml",
  219. "examples/guestbook/redis-slave-service.yaml",
  220. } {
  221. contents := framework.ReadOrDie(gbAppFile)
  222. run(string(contents))
  223. }
  224. }
  225. It("should create and stop a working application [Conformance]", func() {
  226. framework.SkipUnlessServerVersionGTE(deploymentsVersion, c)
  227. defer forEachGBFile(func(contents string) {
  228. cleanupKubectlInputs(contents, ns)
  229. })
  230. By("creating all guestbook components")
  231. forEachGBFile(func(contents string) {
  232. framework.Logf(contents)
  233. framework.RunKubectlOrDieInput(contents, "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  234. })
  235. By("validating guestbook app")
  236. validateGuestbookApp(c, ns)
  237. })
  238. })
  239. framework.KubeDescribe("Simple pod", func() {
  240. var podPath []byte
  241. BeforeEach(func() {
  242. podPath = framework.ReadOrDie(path.Join(kubeCtlManifestPath, "pod-with-readiness-probe.yaml"))
  243. By(fmt.Sprintf("creating the pod from %v", string(podPath)))
  244. framework.RunKubectlOrDieInput(string(podPath[:]), "create", "-f", "-", fmt.Sprintf("--namespace=%v", ns))
  245. Expect(framework.CheckPodsRunningReady(c, ns, []string{simplePodName}, framework.PodStartTimeout)).To(BeTrue())
  246. })
  247. AfterEach(func() {
  248. cleanupKubectlInputs(string(podPath[:]), ns, simplePodSelector)
  249. })
  250. It("should support exec", func() {
  251. By("executing a command in the container")
  252. execOutput := framework.RunKubectlOrDie("exec", fmt.Sprintf("--namespace=%v", ns), simplePodName, "echo", "running", "in", "container")
  253. if e, a := "running in container", strings.TrimSpace(execOutput); e != a {
  254. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
  255. }
  256. By("executing a command in the container with noninteractive stdin")
  257. execOutput = framework.NewKubectlCommand("exec", fmt.Sprintf("--namespace=%v", ns), "-i", simplePodName, "cat").
  258. WithStdinData("abcd1234").
  259. ExecOrDie()
  260. if e, a := "abcd1234", execOutput; e != a {
  261. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
  262. }
  263. // pretend that we're a user in an interactive shell
  264. r, closer, err := newBlockingReader("echo hi\nexit\n")
  265. if err != nil {
  266. framework.Failf("Error creating blocking reader: %v", err)
  267. }
  268. // NOTE this is solely for test cleanup!
  269. defer closer.Close()
  270. By("executing a command in the container with pseudo-interactive stdin")
  271. execOutput = framework.NewKubectlCommand("exec", fmt.Sprintf("--namespace=%v", ns), "-i", simplePodName, "bash").
  272. WithStdinReader(r).
  273. ExecOrDie()
  274. if e, a := "hi", strings.TrimSpace(execOutput); e != a {
  275. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
  276. }
  277. })
  278. It("should support exec through an HTTP proxy", func() {
  279. // Note: We are skipping local since we want to verify an apiserver with HTTPS.
  280. // At this time local only supports plain HTTP.
  281. framework.SkipIfProviderIs("local")
  282. // Fail if the variable isn't set
  283. if framework.TestContext.Host == "" {
  284. framework.Failf("--host variable must be set to the full URI to the api server on e2e run.")
  285. }
  286. By("Starting goproxy")
  287. testSrv, proxyLogs := startLocalProxy()
  288. defer testSrv.Close()
  289. proxyAddr := testSrv.URL
  290. for _, proxyVar := range []string{"https_proxy", "HTTPS_PROXY"} {
  291. proxyLogs.Reset()
  292. By("Running kubectl via an HTTP proxy using " + proxyVar)
  293. output := framework.NewKubectlCommand(fmt.Sprintf("--namespace=%s", ns), "exec", "nginx", "echo", "running", "in", "container").
  294. WithEnv(append(os.Environ(), fmt.Sprintf("%s=%s", proxyVar, proxyAddr))).
  295. ExecOrDie()
  296. // Verify we got the normal output captured by the exec server
  297. expectedExecOutput := "running in container\n"
  298. if output != expectedExecOutput {
  299. framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", expectedExecOutput, output)
  300. }
  301. // Verify the proxy server logs saw the connection
  302. expectedProxyLog := fmt.Sprintf("Accepting CONNECT to %s", strings.TrimRight(strings.TrimLeft(framework.TestContext.Host, "https://"), "/api"))
  303. proxyLog := proxyLogs.String()
  304. if !strings.Contains(proxyLog, expectedProxyLog) {
  305. framework.Failf("Missing expected log result on proxy server for %s. Expected: %q, got %q", proxyVar, expectedProxyLog, proxyLog)
  306. }
  307. }
  308. })
  309. It("should return command exit codes", func() {
  310. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  311. By("execing into a container with a successful command")
  312. _, err := framework.NewKubectlCommand(nsFlag, "exec", "nginx", "--", "/bin/sh", "-c", "exit 0").Exec()
  313. ExpectNoError(err)
  314. By("execing into a container with a failing command")
  315. _, err = framework.NewKubectlCommand(nsFlag, "exec", "nginx", "--", "/bin/sh", "-c", "exit 42").Exec()
  316. ee, ok := err.(uexec.ExitError)
  317. Expect(ok).To(Equal(true))
  318. Expect(ee.ExitStatus()).To(Equal(42))
  319. By("running a successful command")
  320. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=Never", "success", "--", "/bin/sh", "-c", "exit 0").Exec()
  321. ExpectNoError(err)
  322. By("running a failing command")
  323. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=Never", "failure-1", "--", "/bin/sh", "-c", "exit 42").Exec()
  324. ee, ok = err.(uexec.ExitError)
  325. Expect(ok).To(Equal(true))
  326. Expect(ee.ExitStatus()).To(Equal(42))
  327. By("running a failing command without --restart=Never")
  328. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=OnFailure", "failure-2", "--", "/bin/sh", "-c", "cat && exit 42").
  329. WithStdinData("abcd1234").
  330. Exec()
  331. ExpectNoError(err)
  332. By("running a failing command without --restart=Never, but with --rm")
  333. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=OnFailure", "--rm", "failure-3", "--", "/bin/sh", "-c", "cat && exit 42").
  334. WithStdinData("abcd1234").
  335. Exec()
  336. ExpectNoError(err)
  337. framework.WaitForPodToDisappear(f.Client, ns, "failure-3", labels.Everything(), 2*time.Second, wait.ForeverTestTimeout)
  338. By("running a failing command with --leave-stdin-open")
  339. _, err = framework.NewKubectlCommand(nsFlag, "run", "-i", "--image="+busyboxImage, "--restart=Never", "failure-4", "--leave-stdin-open", "--", "/bin/sh", "-c", "exit 42").
  340. WithStdinData("abcd1234").
  341. Exec()
  342. ExpectNoError(err)
  343. })
  344. It("should support inline execution and attach", func() {
  345. framework.SkipIfContainerRuntimeIs("rkt") // #23335
  346. framework.SkipUnlessServerVersionGTE(jobsVersion, c)
  347. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  348. By("executing a command with run and attach with stdin")
  349. runOutput := framework.NewKubectlCommand(nsFlag, "run", "run-test", "--image="+busyboxImage, "--restart=OnFailure", "--attach=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
  350. WithStdinData("abcd1234").
  351. ExecOrDie()
  352. Expect(runOutput).To(ContainSubstring("abcd1234"))
  353. Expect(runOutput).To(ContainSubstring("stdin closed"))
  354. Expect(c.Extensions().Jobs(ns).Delete("run-test", nil)).To(BeNil())
  355. By("executing a command with run and attach without stdin")
  356. 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'").
  357. WithStdinData("abcd1234").
  358. ExecOrDie()
  359. Expect(runOutput).ToNot(ContainSubstring("abcd1234"))
  360. Expect(runOutput).To(ContainSubstring("stdin closed"))
  361. Expect(c.Extensions().Jobs(ns).Delete("run-test-2", nil)).To(BeNil())
  362. By("executing a command with run and attach with stdin with open stdin should remain running")
  363. 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'").
  364. WithStdinData("abcd1234\n").
  365. ExecOrDie()
  366. Expect(runOutput).ToNot(ContainSubstring("stdin closed"))
  367. f := func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) }
  368. runTestPod, _, err := util.GetFirstPod(c, ns, labels.SelectorFromSet(map[string]string{"run": "run-test-3"}), 1*time.Minute, f)
  369. if err != nil {
  370. os.Exit(1)
  371. }
  372. if !framework.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, time.Minute) {
  373. framework.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")
  374. }
  375. // NOTE: we cannot guarantee our output showed up in the container logs before stdin was closed, so we have
  376. // to loop test.
  377. err = wait.PollImmediate(time.Second, time.Minute, func() (bool, error) {
  378. if !framework.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, 1*time.Second) {
  379. framework.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")
  380. }
  381. logOutput := framework.RunKubectlOrDie(nsFlag, "logs", runTestPod.Name)
  382. Expect(logOutput).ToNot(ContainSubstring("stdin closed"))
  383. return strings.Contains(logOutput, "abcd1234"), nil
  384. })
  385. if err != nil {
  386. os.Exit(1)
  387. }
  388. Expect(err).To(BeNil())
  389. Expect(c.Extensions().Jobs(ns).Delete("run-test-3", nil)).To(BeNil())
  390. })
  391. It("should support port-forward", func() {
  392. By("forwarding the container port to a local port")
  393. cmd := runPortForward(ns, simplePodName, simplePodPort)
  394. defer cmd.Stop()
  395. By("curling local port output")
  396. localAddr := fmt.Sprintf("http://localhost:%d", cmd.port)
  397. body, err := curl(localAddr)
  398. framework.Logf("got: %s", body)
  399. if err != nil {
  400. framework.Failf("Failed http.Get of forwarded port (%s): %v", localAddr, err)
  401. }
  402. if !strings.Contains(body, nginxDefaultOutput) {
  403. framework.Failf("Container port output missing expected value. Wanted:'%s', got: %s", nginxDefaultOutput, body)
  404. }
  405. })
  406. })
  407. framework.KubeDescribe("Kubectl api-versions", func() {
  408. It("should check if v1 is in available api versions [Conformance]", func() {
  409. By("validating api verions")
  410. output := framework.RunKubectlOrDie("api-versions")
  411. if !strings.Contains(output, "v1") {
  412. framework.Failf("No v1 in kubectl api-versions")
  413. }
  414. })
  415. })
  416. framework.KubeDescribe("Kubectl apply", func() {
  417. It("should apply a new configuration to an existing RC", func() {
  418. controllerJson := readTestFileOrDie(redisControllerFilename)
  419. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  420. By("creating Redis RC")
  421. framework.RunKubectlOrDieInput(string(controllerJson), "create", "-f", "-", nsFlag)
  422. By("applying a modified configuration")
  423. stdin := modifyReplicationControllerConfiguration(string(controllerJson))
  424. framework.NewKubectlCommand("apply", "-f", "-", nsFlag).
  425. WithStdinReader(stdin).
  426. ExecOrDie()
  427. By("checking the result")
  428. forEachReplicationController(c, ns, "app", "redis", validateReplicationControllerConfiguration)
  429. })
  430. It("should reuse nodePort when apply to an existing SVC", func() {
  431. serviceJson := readTestFileOrDie(redisServiceFilename)
  432. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  433. By("creating Redis SVC")
  434. framework.RunKubectlOrDieInput(string(serviceJson[:]), "create", "-f", "-", nsFlag)
  435. By("getting the original nodePort")
  436. originalNodePort := framework.RunKubectlOrDie("get", "service", "redis-master", nsFlag, "-o", "jsonpath={.spec.ports[0].nodePort}")
  437. By("applying the same configuration")
  438. framework.RunKubectlOrDieInput(string(serviceJson[:]), "apply", "-f", "-", nsFlag)
  439. By("getting the nodePort after applying configuration")
  440. currentNodePort := framework.RunKubectlOrDie("get", "service", "redis-master", nsFlag, "-o", "jsonpath={.spec.ports[0].nodePort}")
  441. By("checking the result")
  442. if originalNodePort != currentNodePort {
  443. framework.Failf("nodePort should keep the same")
  444. }
  445. })
  446. })
  447. framework.KubeDescribe("Kubectl cluster-info", func() {
  448. It("should check if Kubernetes master services is included in cluster-info [Conformance]", func() {
  449. By("validating cluster-info")
  450. output := framework.RunKubectlOrDie("cluster-info")
  451. // Can't check exact strings due to terminal control commands (colors)
  452. requiredItems := []string{"Kubernetes master", "is running at"}
  453. if framework.ProviderIs("gce", "gke") {
  454. requiredItems = append(requiredItems, "KubeDNS", "Heapster")
  455. }
  456. for _, item := range requiredItems {
  457. if !strings.Contains(output, item) {
  458. framework.Failf("Missing %s in kubectl cluster-info", item)
  459. }
  460. }
  461. })
  462. })
  463. framework.KubeDescribe("Kubectl describe", func() {
  464. It("should check if kubectl describe prints relevant information for rc and pods [Conformance]", func() {
  465. framework.SkipUnlessServerVersionGTE(nodePortsOptionalVersion, c)
  466. controllerJson := readTestFileOrDie(redisControllerFilename)
  467. serviceJson := readTestFileOrDie(redisServiceFilename)
  468. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  469. framework.RunKubectlOrDieInput(string(controllerJson[:]), "create", "-f", "-", nsFlag)
  470. framework.RunKubectlOrDieInput(string(serviceJson[:]), "create", "-f", "-", nsFlag)
  471. By("Waiting for Redis master to start.")
  472. waitForOrFailWithDebug(1)
  473. // Pod
  474. forEachPod(func(pod api.Pod) {
  475. output := framework.RunKubectlOrDie("describe", "pod", pod.Name, nsFlag)
  476. requiredStrings := [][]string{
  477. {"Name:", "redis-master-"},
  478. {"Namespace:", ns},
  479. {"Node:"},
  480. {"Labels:", "app=redis"},
  481. {"role=master"},
  482. {"Status:", "Running"},
  483. {"IP:"},
  484. {"Controllers:", "ReplicationController/redis-master"},
  485. {"Image:", redisImage},
  486. {"State:", "Running"},
  487. {"QoS Class:", "BestEffort"},
  488. }
  489. checkOutput(output, requiredStrings)
  490. })
  491. // Rc
  492. output := framework.RunKubectlOrDie("describe", "rc", "redis-master", nsFlag)
  493. requiredStrings := [][]string{
  494. {"Name:", "redis-master"},
  495. {"Namespace:", ns},
  496. {"Image(s):", redisImage},
  497. {"Selector:", "app=redis,role=master"},
  498. {"Labels:", "app=redis"},
  499. {"role=master"},
  500. {"Replicas:", "1 current", "1 desired"},
  501. {"Pods Status:", "1 Running", "0 Waiting", "0 Succeeded", "0 Failed"},
  502. // {"Events:"} would ordinarily go in the list
  503. // here, but in some rare circumstances the
  504. // events are delayed, and instead kubectl
  505. // prints "No events." This string will match
  506. // either way.
  507. {"vents"}}
  508. checkOutput(output, requiredStrings)
  509. // Service
  510. output = framework.RunKubectlOrDie("describe", "service", "redis-master", nsFlag)
  511. requiredStrings = [][]string{
  512. {"Name:", "redis-master"},
  513. {"Namespace:", ns},
  514. {"Labels:", "app=redis"},
  515. {"role=master"},
  516. {"Selector:", "app=redis", "role=master"},
  517. {"Type:", "ClusterIP"},
  518. {"IP:"},
  519. {"Port:", "<unset>", "6379/TCP"},
  520. {"Endpoints:"},
  521. {"Session Affinity:", "None"}}
  522. checkOutput(output, requiredStrings)
  523. // Node
  524. // It should be OK to list unschedulable Nodes here.
  525. nodes, err := c.Nodes().List(api.ListOptions{})
  526. Expect(err).NotTo(HaveOccurred())
  527. node := nodes.Items[0]
  528. output = framework.RunKubectlOrDie("describe", "node", node.Name)
  529. requiredStrings = [][]string{
  530. {"Name:", node.Name},
  531. {"Labels:"},
  532. {"CreationTimestamp:"},
  533. {"Conditions:"},
  534. {"Type", "Status", "LastHeartbeatTime", "LastTransitionTime", "Reason", "Message"},
  535. {"Addresses:"},
  536. {"Capacity:"},
  537. {"Version:"},
  538. {"Kernel Version:"},
  539. {"OS Image:"},
  540. {"Container Runtime Version:"},
  541. {"Kubelet Version:"},
  542. {"Kube-Proxy Version:"},
  543. {"Pods:"}}
  544. checkOutput(output, requiredStrings)
  545. // Namespace
  546. output = framework.RunKubectlOrDie("describe", "namespace", ns)
  547. requiredStrings = [][]string{
  548. {"Name:", ns},
  549. {"Labels:"},
  550. {"Status:", "Active"}}
  551. checkOutput(output, requiredStrings)
  552. // Quota and limitrange are skipped for now.
  553. })
  554. })
  555. framework.KubeDescribe("Kubectl expose", func() {
  556. It("should create services for rc [Conformance]", func() {
  557. controllerJson := readTestFileOrDie(redisControllerFilename)
  558. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  559. redisPort := 6379
  560. By("creating Redis RC")
  561. framework.Logf("namespace %v", ns)
  562. framework.RunKubectlOrDieInput(string(controllerJson[:]), "create", "-f", "-", nsFlag)
  563. // It may take a while for the pods to get registered in some cases, wait to be sure.
  564. By("Waiting for Redis master to start.")
  565. waitForOrFailWithDebug(1)
  566. forEachPod(func(pod api.Pod) {
  567. framework.Logf("wait on redis-master startup in %v ", ns)
  568. framework.LookForStringInLog(ns, pod.Name, "redis-master", "The server is now ready to accept connections", framework.PodStartTimeout)
  569. })
  570. validateService := func(name string, servicePort int, timeout time.Duration) {
  571. err := wait.Poll(framework.Poll, timeout, func() (bool, error) {
  572. endpoints, err := c.Endpoints(ns).Get(name)
  573. if err != nil {
  574. if apierrs.IsNotFound(err) {
  575. err = nil
  576. }
  577. framework.Logf("Get endpoints failed (interval %v): %v", framework.Poll, err)
  578. return false, err
  579. }
  580. uidToPort := getContainerPortsByPodUID(endpoints)
  581. if len(uidToPort) == 0 {
  582. framework.Logf("No endpoint found, retrying")
  583. return false, nil
  584. }
  585. if len(uidToPort) > 1 {
  586. Fail("Too many endpoints found")
  587. }
  588. for _, port := range uidToPort {
  589. if port[0] != redisPort {
  590. framework.Failf("Wrong endpoint port: %d", port[0])
  591. }
  592. }
  593. return true, nil
  594. })
  595. Expect(err).NotTo(HaveOccurred())
  596. service, err := c.Services(ns).Get(name)
  597. Expect(err).NotTo(HaveOccurred())
  598. if len(service.Spec.Ports) != 1 {
  599. framework.Failf("1 port is expected")
  600. }
  601. port := service.Spec.Ports[0]
  602. if port.Port != int32(servicePort) {
  603. framework.Failf("Wrong service port: %d", port.Port)
  604. }
  605. if port.TargetPort.IntValue() != redisPort {
  606. framework.Failf("Wrong target port: %d")
  607. }
  608. }
  609. By("exposing RC")
  610. framework.RunKubectlOrDie("expose", "rc", "redis-master", "--name=rm2", "--port=1234", fmt.Sprintf("--target-port=%d", redisPort), nsFlag)
  611. framework.WaitForService(c, ns, "rm2", true, framework.Poll, framework.ServiceStartTimeout)
  612. validateService("rm2", 1234, framework.ServiceStartTimeout)
  613. By("exposing service")
  614. framework.RunKubectlOrDie("expose", "service", "rm2", "--name=rm3", "--port=2345", fmt.Sprintf("--target-port=%d", redisPort), nsFlag)
  615. framework.WaitForService(c, ns, "rm3", true, framework.Poll, framework.ServiceStartTimeout)
  616. validateService("rm3", 2345, framework.ServiceStartTimeout)
  617. })
  618. })
  619. framework.KubeDescribe("Kubectl label", func() {
  620. var pod []byte
  621. var nsFlag string
  622. BeforeEach(func() {
  623. pod = readTestFileOrDie("pause-pod.yaml")
  624. By("creating the pod")
  625. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  626. framework.RunKubectlOrDieInput(string(pod), "create", "-f", "-", nsFlag)
  627. Expect(framework.CheckPodsRunningReady(c, ns, []string{pausePodName}, framework.PodStartTimeout)).To(BeTrue())
  628. })
  629. AfterEach(func() {
  630. cleanupKubectlInputs(string(pod[:]), ns, pausePodSelector)
  631. })
  632. It("should update the label on a resource [Conformance]", func() {
  633. labelName := "testing-label"
  634. labelValue := "testing-label-value"
  635. By("adding the label " + labelName + " with value " + labelValue + " to a pod")
  636. framework.RunKubectlOrDie("label", "pods", pausePodName, labelName+"="+labelValue, nsFlag)
  637. By("verifying the pod has the label " + labelName + " with the value " + labelValue)
  638. output := framework.RunKubectlOrDie("get", "pod", pausePodName, "-L", labelName, nsFlag)
  639. if !strings.Contains(output, labelValue) {
  640. framework.Failf("Failed updating label " + labelName + " to the pod " + pausePodName)
  641. }
  642. By("removing the label " + labelName + " of a pod")
  643. framework.RunKubectlOrDie("label", "pods", pausePodName, labelName+"-", nsFlag)
  644. By("verifying the pod doesn't have the label " + labelName)
  645. output = framework.RunKubectlOrDie("get", "pod", pausePodName, "-L", labelName, nsFlag)
  646. if strings.Contains(output, labelValue) {
  647. framework.Failf("Failed removing label " + labelName + " of the pod " + pausePodName)
  648. }
  649. })
  650. })
  651. framework.KubeDescribe("Kubectl logs", func() {
  652. var rc []byte
  653. var nsFlag string
  654. containerName := "redis-master"
  655. BeforeEach(func() {
  656. rc = readTestFileOrDie(redisControllerFilename)
  657. By("creating an rc")
  658. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  659. framework.RunKubectlOrDieInput(string(rc[:]), "create", "-f", "-", nsFlag)
  660. })
  661. AfterEach(func() {
  662. cleanupKubectlInputs(string(rc[:]), ns, simplePodSelector)
  663. })
  664. It("should be able to retrieve and filter logs [Conformance]", func() {
  665. framework.SkipUnlessServerVersionGTE(extendedPodLogFilterVersion, c)
  666. // Split("something\n", "\n") returns ["something", ""], so
  667. // strip trailing newline first
  668. lines := func(out string) []string {
  669. return strings.Split(strings.TrimRight(out, "\n"), "\n")
  670. }
  671. By("Waiting for Redis master to start.")
  672. waitForOrFailWithDebug(1)
  673. forEachPod(func(pod api.Pod) {
  674. By("checking for a matching strings")
  675. _, err := framework.LookForStringInLog(ns, pod.Name, containerName, "The server is now ready to accept connections", framework.PodStartTimeout)
  676. Expect(err).NotTo(HaveOccurred())
  677. By("limiting log lines")
  678. out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--tail=1")
  679. Expect(len(out)).NotTo(BeZero())
  680. Expect(len(lines(out))).To(Equal(1))
  681. By("limiting log bytes")
  682. out = framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--limit-bytes=1")
  683. Expect(len(lines(out))).To(Equal(1))
  684. Expect(len(out)).To(Equal(1))
  685. By("exposing timestamps")
  686. out = framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--tail=1", "--timestamps")
  687. l := lines(out)
  688. Expect(len(l)).To(Equal(1))
  689. words := strings.Split(l[0], " ")
  690. Expect(len(words)).To(BeNumerically(">", 1))
  691. if _, err := time.Parse(time.RFC3339Nano, words[0]); err != nil {
  692. if _, err := time.Parse(time.RFC3339, words[0]); err != nil {
  693. framework.Failf("expected %q to be RFC3339 or RFC3339Nano", words[0])
  694. }
  695. }
  696. By("restricting to a time range")
  697. // Note: we must wait at least two seconds,
  698. // because the granularity is only 1 second and
  699. // it could end up rounding the wrong way.
  700. time.Sleep(2500 * time.Millisecond) // ensure that startup logs on the node are seen as older than 1s
  701. recent_out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--since=1s")
  702. recent := len(strings.Split(recent_out, "\n"))
  703. older_out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--since=24h")
  704. older := len(strings.Split(older_out, "\n"))
  705. 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)
  706. })
  707. })
  708. })
  709. framework.KubeDescribe("Kubectl patch", func() {
  710. It("should add annotations for pods in rc [Conformance]", func() {
  711. controllerJson := readTestFileOrDie(redisControllerFilename)
  712. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  713. By("creating Redis RC")
  714. framework.RunKubectlOrDieInput(string(controllerJson[:]), "create", "-f", "-", nsFlag)
  715. By("Waiting for Redis master to start.")
  716. waitForOrFailWithDebug(1)
  717. By("patching all pods")
  718. forEachPod(func(pod api.Pod) {
  719. framework.RunKubectlOrDie("patch", "pod", pod.Name, nsFlag, "-p", "{\"metadata\":{\"annotations\":{\"x\":\"y\"}}}")
  720. })
  721. By("checking annotations")
  722. forEachPod(func(pod api.Pod) {
  723. found := false
  724. for key, val := range pod.Annotations {
  725. if key == "x" && val == "y" {
  726. found = true
  727. }
  728. }
  729. if !found {
  730. framework.Failf("Added annotation not found")
  731. }
  732. })
  733. })
  734. })
  735. framework.KubeDescribe("Kubectl version", func() {
  736. It("should check is all data is printed [Conformance]", func() {
  737. version := framework.RunKubectlOrDie("version")
  738. requiredItems := []string{"Client Version:", "Server Version:", "Major:", "Minor:", "GitCommit:"}
  739. for _, item := range requiredItems {
  740. if !strings.Contains(version, item) {
  741. framework.Failf("Required item %s not found in %s", item, version)
  742. }
  743. }
  744. })
  745. })
  746. framework.KubeDescribe("Kubectl run default", func() {
  747. var nsFlag string
  748. var name string
  749. var cleanUp func()
  750. BeforeEach(func() {
  751. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  752. gte, err := framework.ServerVersionGTE(deploymentsVersion, c)
  753. if err != nil {
  754. framework.Failf("Failed to get server version: %v", err)
  755. }
  756. if gte {
  757. name = "e2e-test-nginx-deployment"
  758. cleanUp = func() { framework.RunKubectlOrDie("delete", "deployment", name, nsFlag) }
  759. } else {
  760. name = "e2e-test-nginx-rc"
  761. cleanUp = func() { framework.RunKubectlOrDie("delete", "rc", name, nsFlag) }
  762. }
  763. })
  764. AfterEach(func() {
  765. cleanUp()
  766. })
  767. It("should create an rc or deployment from an image [Conformance]", func() {
  768. By("running the image " + nginxImage)
  769. framework.RunKubectlOrDie("run", name, "--image="+nginxImage, nsFlag)
  770. By("verifying the pod controlled by " + name + " gets created")
  771. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": name}))
  772. podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
  773. if err != nil {
  774. framework.Failf("Failed getting pod controlled by %s: %v", name, err)
  775. }
  776. pods := podlist.Items
  777. if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
  778. framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
  779. framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
  780. }
  781. })
  782. })
  783. framework.KubeDescribe("Kubectl run rc", func() {
  784. var nsFlag string
  785. var rcName string
  786. BeforeEach(func() {
  787. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  788. rcName = "e2e-test-nginx-rc"
  789. })
  790. AfterEach(func() {
  791. framework.RunKubectlOrDie("delete", "rc", rcName, nsFlag)
  792. })
  793. It("should create an rc from an image [Conformance]", func() {
  794. By("running the image " + nginxImage)
  795. framework.RunKubectlOrDie("run", rcName, "--image="+nginxImage, "--generator=run/v1", nsFlag)
  796. By("verifying the rc " + rcName + " was created")
  797. rc, err := c.ReplicationControllers(ns).Get(rcName)
  798. if err != nil {
  799. framework.Failf("Failed getting rc %s: %v", rcName, err)
  800. }
  801. containers := rc.Spec.Template.Spec.Containers
  802. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  803. framework.Failf("Failed creating rc %s for 1 pod with expected image %s", rcName, nginxImage)
  804. }
  805. By("verifying the pod controlled by rc " + rcName + " was created")
  806. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": rcName}))
  807. podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
  808. if err != nil {
  809. framework.Failf("Failed getting pod controlled by rc %s: %v", rcName, err)
  810. }
  811. pods := podlist.Items
  812. if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
  813. framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
  814. framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
  815. }
  816. By("confirm that you can get logs from an rc")
  817. podNames := []string{}
  818. for _, pod := range pods {
  819. podNames = append(podNames, pod.Name)
  820. }
  821. if !framework.CheckPodsRunningReady(c, ns, podNames, framework.PodStartTimeout) {
  822. framework.Failf("Pods for rc %s were not ready", rcName)
  823. }
  824. _, err = framework.RunKubectl("logs", "rc/"+rcName, nsFlag)
  825. // a non-nil error is fine as long as we actually found a pod.
  826. if err != nil && !strings.Contains(err.Error(), " in pod ") {
  827. framework.Failf("Failed getting logs by rc %s: %v", rcName, err)
  828. }
  829. })
  830. })
  831. framework.KubeDescribe("Kubectl rolling-update", func() {
  832. var nsFlag string
  833. var rcName string
  834. var c *client.Client
  835. BeforeEach(func() {
  836. c = f.Client
  837. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  838. rcName = "e2e-test-nginx-rc"
  839. })
  840. AfterEach(func() {
  841. framework.RunKubectlOrDie("delete", "rc", rcName, nsFlag)
  842. })
  843. It("should support rolling-update to same image [Conformance]", func() {
  844. By("running the image " + nginxImage)
  845. framework.RunKubectlOrDie("run", rcName, "--image="+nginxImage, "--generator=run/v1", nsFlag)
  846. By("verifying the rc " + rcName + " was created")
  847. rc, err := c.ReplicationControllers(ns).Get(rcName)
  848. if err != nil {
  849. framework.Failf("Failed getting rc %s: %v", rcName, err)
  850. }
  851. containers := rc.Spec.Template.Spec.Containers
  852. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  853. framework.Failf("Failed creating rc %s for 1 pod with expected image %s", rcName, nginxImage)
  854. }
  855. framework.WaitForRCToStabilize(c, ns, rcName, framework.PodStartTimeout)
  856. By("rolling-update to same image controller")
  857. runKubectlRetryOrDie("rolling-update", rcName, "--update-period=1s", "--image="+nginxImage, "--image-pull-policy="+string(api.PullIfNotPresent), nsFlag)
  858. framework.ValidateController(c, nginxImage, 1, rcName, "run="+rcName, noOpValidatorFn, ns)
  859. })
  860. })
  861. framework.KubeDescribe("Kubectl run deployment", func() {
  862. var nsFlag string
  863. var dName string
  864. BeforeEach(func() {
  865. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  866. dName = "e2e-test-nginx-deployment"
  867. })
  868. AfterEach(func() {
  869. framework.RunKubectlOrDie("delete", "deployment", dName, nsFlag)
  870. })
  871. It("should create a deployment from an image [Conformance]", func() {
  872. framework.SkipUnlessServerVersionGTE(deploymentsVersion, c)
  873. By("running the image " + nginxImage)
  874. framework.RunKubectlOrDie("run", dName, "--image="+nginxImage, "--generator=deployment/v1beta1", nsFlag)
  875. By("verifying the deployment " + dName + " was created")
  876. d, err := c.Extensions().Deployments(ns).Get(dName)
  877. if err != nil {
  878. framework.Failf("Failed getting deployment %s: %v", dName, err)
  879. }
  880. containers := d.Spec.Template.Spec.Containers
  881. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  882. framework.Failf("Failed creating deployment %s for 1 pod with expected image %s", dName, nginxImage)
  883. }
  884. By("verifying the pod controlled by deployment " + dName + " was created")
  885. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": dName}))
  886. podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
  887. if err != nil {
  888. framework.Failf("Failed getting pod controlled by deployment %s: %v", dName, err)
  889. }
  890. pods := podlist.Items
  891. if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
  892. framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
  893. framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
  894. }
  895. })
  896. })
  897. framework.KubeDescribe("Kubectl run job", func() {
  898. var nsFlag string
  899. var jobName string
  900. BeforeEach(func() {
  901. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  902. jobName = "e2e-test-nginx-job"
  903. })
  904. AfterEach(func() {
  905. framework.RunKubectlOrDie("delete", "jobs", jobName, nsFlag)
  906. })
  907. It("should create a job from an image when restart is OnFailure [Conformance]", func() {
  908. framework.SkipUnlessServerVersionGTE(jobsVersion, c)
  909. By("running the image " + nginxImage)
  910. framework.RunKubectlOrDie("run", jobName, "--restart=OnFailure", "--generator=job/v1", "--image="+nginxImage, nsFlag)
  911. By("verifying the job " + jobName + " was created")
  912. job, err := c.Extensions().Jobs(ns).Get(jobName)
  913. if err != nil {
  914. framework.Failf("Failed getting job %s: %v", jobName, err)
  915. }
  916. containers := job.Spec.Template.Spec.Containers
  917. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  918. framework.Failf("Failed creating job %s for 1 pod with expected image %s", jobName, nginxImage)
  919. }
  920. if job.Spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure {
  921. framework.Failf("Failed creating a job with correct restart policy for --restart=OnFailure")
  922. }
  923. })
  924. })
  925. framework.KubeDescribe("Kubectl run pod", func() {
  926. var nsFlag string
  927. var podName string
  928. BeforeEach(func() {
  929. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  930. podName = "e2e-test-nginx-pod"
  931. })
  932. AfterEach(func() {
  933. framework.RunKubectlOrDie("delete", "pods", podName, nsFlag)
  934. })
  935. It("should create a pod from an image when restart is Never [Conformance]", func() {
  936. framework.SkipUnlessServerVersionGTE(jobsVersion, c)
  937. By("running the image " + nginxImage)
  938. framework.RunKubectlOrDie("run", podName, "--restart=Never", "--generator=run-pod/v1", "--image="+nginxImage, nsFlag)
  939. By("verifying the pod " + podName + " was created")
  940. pod, err := c.Pods(ns).Get(podName)
  941. if err != nil {
  942. framework.Failf("Failed getting pod %s: %v", podName, err)
  943. }
  944. containers := pod.Spec.Containers
  945. if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
  946. framework.Failf("Failed creating pod %s with expected image %s", podName, nginxImage)
  947. }
  948. if pod.Spec.RestartPolicy != api.RestartPolicyNever {
  949. framework.Failf("Failed creating a pod with correct restart policy for --restart=Never")
  950. }
  951. })
  952. })
  953. framework.KubeDescribe("Kubectl replace", func() {
  954. var nsFlag string
  955. var podName string
  956. BeforeEach(func() {
  957. nsFlag = fmt.Sprintf("--namespace=%v", ns)
  958. podName = "e2e-test-nginx-pod"
  959. })
  960. AfterEach(func() {
  961. framework.RunKubectlOrDie("delete", "pods", podName, nsFlag)
  962. })
  963. It("should update a single-container pod's image [Conformance]", func() {
  964. framework.SkipUnlessServerVersionGTE(jobsVersion, c)
  965. By("running the image " + nginxImage)
  966. framework.RunKubectlOrDie("run", podName, "--generator=run-pod/v1", "--image="+nginxImage, "--labels=run="+podName, nsFlag)
  967. By("verifying the pod " + podName + " is running")
  968. label := labels.SelectorFromSet(labels.Set(map[string]string{"run": podName}))
  969. err := framework.WaitForPodsWithLabelRunning(c, ns, label)
  970. if err != nil {
  971. framework.Failf("Failed getting pod %s: %v", podName, err)
  972. }
  973. By("verifying the pod " + podName + " was created")
  974. podJson := framework.RunKubectlOrDie("get", "pod", podName, nsFlag, "-o", "json")
  975. if !strings.Contains(podJson, podName) {
  976. framework.Failf("Failed to find pod %s in [%s]", podName, podJson)
  977. }
  978. By("replace the image in the pod")
  979. podJson = strings.Replace(podJson, nginxImage, busyboxImage, 1)
  980. framework.RunKubectlOrDieInput(podJson, "replace", "-f", "-", nsFlag)
  981. By("verifying the pod " + podName + " has the right image " + busyboxImage)
  982. pod, err := c.Pods(ns).Get(podName)
  983. if err != nil {
  984. framework.Failf("Failed getting deployment %s: %v", podName, err)
  985. }
  986. containers := pod.Spec.Containers
  987. if containers == nil || len(containers) != 1 || containers[0].Image != busyboxImage {
  988. framework.Failf("Failed creating pod with expected image %s", busyboxImage)
  989. }
  990. })
  991. })
  992. framework.KubeDescribe("Kubectl run --rm job", func() {
  993. jobName := "e2e-test-rm-busybox-job"
  994. It("should create a job from an image, then delete the job [Conformance]", func() {
  995. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  996. // The rkt runtime doesn't support attach, see #23335
  997. framework.SkipIfContainerRuntimeIs("rkt")
  998. framework.SkipUnlessServerVersionGTE(jobsVersion, c)
  999. By("executing a command with run --rm and attach with stdin")
  1000. t := time.NewTimer(runJobTimeout)
  1001. defer t.Stop()
  1002. runOutput := framework.NewKubectlCommand(nsFlag, "run", jobName, "--image="+busyboxImage, "--rm=true", "--generator=job/v1", "--restart=OnFailure", "--attach=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
  1003. WithStdinData("abcd1234").
  1004. WithTimeout(t.C).
  1005. ExecOrDie()
  1006. Expect(runOutput).To(ContainSubstring("abcd1234"))
  1007. Expect(runOutput).To(ContainSubstring("stdin closed"))
  1008. By("verifying the job " + jobName + " was deleted")
  1009. _, err := c.Extensions().Jobs(ns).Get(jobName)
  1010. Expect(err).To(HaveOccurred())
  1011. Expect(apierrs.IsNotFound(err)).To(BeTrue())
  1012. })
  1013. })
  1014. framework.KubeDescribe("Proxy server", func() {
  1015. // TODO: test proxy options (static, prefix, etc)
  1016. It("should support proxy with --port 0 [Conformance]", func() {
  1017. By("starting the proxy server")
  1018. port, cmd, err := startProxyServer()
  1019. if cmd != nil {
  1020. defer framework.TryKill(cmd)
  1021. }
  1022. if err != nil {
  1023. framework.Failf("Failed to start proxy server: %v", err)
  1024. }
  1025. By("curling proxy /api/ output")
  1026. localAddr := fmt.Sprintf("http://localhost:%d/api/", port)
  1027. apiVersions, err := getAPIVersions(localAddr)
  1028. if err != nil {
  1029. framework.Failf("Expected at least one supported apiversion, got error %v", err)
  1030. }
  1031. if len(apiVersions.Versions) < 1 {
  1032. framework.Failf("Expected at least one supported apiversion, got %v", apiVersions)
  1033. }
  1034. })
  1035. It("should support --unix-socket=/path [Conformance]", func() {
  1036. By("Starting the proxy")
  1037. tmpdir, err := ioutil.TempDir("", "kubectl-proxy-unix")
  1038. if err != nil {
  1039. framework.Failf("Failed to create temporary directory: %v", err)
  1040. }
  1041. path := filepath.Join(tmpdir, "test")
  1042. defer os.Remove(path)
  1043. defer os.Remove(tmpdir)
  1044. cmd := framework.KubectlCmd("proxy", fmt.Sprintf("--unix-socket=%s", path))
  1045. stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)
  1046. if err != nil {
  1047. framework.Failf("Failed to start kubectl command: %v", err)
  1048. }
  1049. defer stdout.Close()
  1050. defer stderr.Close()
  1051. defer framework.TryKill(cmd)
  1052. buf := make([]byte, 128)
  1053. if _, err = stdout.Read(buf); err != nil {
  1054. framework.Failf("Expected output from kubectl proxy: %v", err)
  1055. }
  1056. By("retrieving proxy /api/ output")
  1057. _, err = curlUnix("http://unused/api", path)
  1058. if err != nil {
  1059. framework.Failf("Failed get of /api at %s: %v", path, err)
  1060. }
  1061. })
  1062. })
  1063. framework.KubeDescribe("Kubectl taint", func() {
  1064. It("should update the taint on a node", func() {
  1065. taintName := fmt.Sprintf("kubernetes.io/e2e-taint-key-%s", string(uuid.NewUUID()))
  1066. taintValue := "testing-taint-value"
  1067. taintEffect := fmt.Sprintf("%s", api.TaintEffectNoSchedule)
  1068. nodes, err := c.Nodes().List(api.ListOptions{})
  1069. Expect(err).NotTo(HaveOccurred())
  1070. node := nodes.Items[0]
  1071. nodeName := node.Name
  1072. By("adding the taint " + taintName + " with value " + taintValue + " and taint effect " + taintEffect + " to a node")
  1073. framework.RunKubectlOrDie("taint", "nodes", nodeName, taintName+"="+taintValue+":"+taintEffect)
  1074. By("verifying the node has the taint " + taintName + " with the value " + taintValue)
  1075. output := framework.RunKubectlOrDie("describe", "node", nodeName)
  1076. requiredStrings := [][]string{
  1077. {"Name:", nodeName},
  1078. {"Taints:"},
  1079. {taintName + "=" + taintValue + ":" + taintEffect},
  1080. }
  1081. checkOutput(output, requiredStrings)
  1082. By("removing the taint " + taintName + " of a node")
  1083. framework.RunKubectlOrDie("taint", "nodes", nodeName, taintName+":"+taintEffect+"-")
  1084. By("verifying the node doesn't have the taint " + taintName)
  1085. output = framework.RunKubectlOrDie("describe", "node", nodeName)
  1086. if strings.Contains(output, taintName) {
  1087. framework.Failf("Failed removing taint " + taintName + " of the node " + nodeName)
  1088. }
  1089. })
  1090. It("should remove all the taints with the same key off a node", func() {
  1091. taintName := fmt.Sprintf("kubernetes.io/e2e-taint-key-%s", string(uuid.NewUUID()))
  1092. taintValue := "testing-taint-value"
  1093. taintEffect := fmt.Sprintf("%s", api.TaintEffectNoSchedule)
  1094. nodes, err := c.Nodes().List(api.ListOptions{})
  1095. Expect(err).NotTo(HaveOccurred())
  1096. node := nodes.Items[0]
  1097. nodeName := node.Name
  1098. By("adding the taint " + taintName + " with value " + taintValue + " and taint effect " + taintEffect + " to a node")
  1099. framework.RunKubectlOrDie("taint", "nodes", nodeName, taintName+"="+taintValue+":"+taintEffect)
  1100. By("verifying the node has the taint " + taintName + " with the value " + taintValue)
  1101. output := framework.RunKubectlOrDie("describe", "node", nodeName)
  1102. requiredStrings := [][]string{
  1103. {"Name:", nodeName},
  1104. {"Taints:"},
  1105. {taintName + "=" + taintValue + ":" + taintEffect},
  1106. }
  1107. checkOutput(output, requiredStrings)
  1108. newTaintValue := "another-testing-taint-value"
  1109. newTaintEffect := fmt.Sprintf("%s", api.TaintEffectPreferNoSchedule)
  1110. By("adding another taint " + taintName + " with value " + newTaintValue + " and taint effect " + newTaintEffect + " to the node")
  1111. framework.RunKubectlOrDie("taint", "nodes", nodeName, taintName+"="+newTaintValue+":"+newTaintEffect)
  1112. By("verifying the node has the taint " + taintName + " with the value " + newTaintValue)
  1113. output = framework.RunKubectlOrDie("describe", "node", nodeName)
  1114. requiredStrings = [][]string{
  1115. {"Name:", nodeName},
  1116. {"Taints:"},
  1117. {taintName + "=" + newTaintValue + ":" + newTaintEffect},
  1118. }
  1119. checkOutput(output, requiredStrings)
  1120. By("removing the taint " + taintName + " of a node")
  1121. framework.RunKubectlOrDie("taint", "nodes", nodeName, taintName+"-")
  1122. By("verifying the node doesn't have the taints " + taintName)
  1123. output = framework.RunKubectlOrDie("describe", "node", nodeName)
  1124. if strings.Contains(output, taintName) {
  1125. framework.Failf("Failed removing taint " + taintName + " of the node " + nodeName)
  1126. }
  1127. })
  1128. })
  1129. framework.KubeDescribe("Kubectl create quota", func() {
  1130. It("should create a quota without scopes", func() {
  1131. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1132. quotaName := "million"
  1133. By("calling kubectl quota")
  1134. framework.RunKubectlOrDie("create", "quota", quotaName, "--hard=pods=1000000,services=1000000", nsFlag)
  1135. By("verifying that the quota was created")
  1136. quota, err := c.ResourceQuotas(ns).Get(quotaName)
  1137. if err != nil {
  1138. framework.Failf("Failed getting quota %s: %v", quotaName, err)
  1139. }
  1140. if len(quota.Spec.Scopes) != 0 {
  1141. framework.Failf("Expected empty scopes, got %v", quota.Spec.Scopes)
  1142. }
  1143. if len(quota.Spec.Hard) != 2 {
  1144. framework.Failf("Expected two resources, got %v", quota.Spec.Hard)
  1145. }
  1146. r, found := quota.Spec.Hard[api.ResourcePods]
  1147. if expected := resource.MustParse("1000000"); !found || (&r).Cmp(expected) != 0 {
  1148. framework.Failf("Expected pods=1000000, got %v", r)
  1149. }
  1150. r, found = quota.Spec.Hard[api.ResourceServices]
  1151. if expected := resource.MustParse("1000000"); !found || (&r).Cmp(expected) != 0 {
  1152. framework.Failf("Expected services=1000000, got %v", r)
  1153. }
  1154. })
  1155. It("should create a quota with scopes", func() {
  1156. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1157. quotaName := "scopes"
  1158. By("calling kubectl quota")
  1159. framework.RunKubectlOrDie("create", "quota", quotaName, "--hard=pods=1000000", "--scopes=BestEffort,NotTerminating", nsFlag)
  1160. By("verifying that the quota was created")
  1161. quota, err := c.ResourceQuotas(ns).Get(quotaName)
  1162. if err != nil {
  1163. framework.Failf("Failed getting quota %s: %v", quotaName, err)
  1164. }
  1165. if len(quota.Spec.Scopes) != 2 {
  1166. framework.Failf("Expected two scopes, got %v", quota.Spec.Scopes)
  1167. }
  1168. scopes := make(map[api.ResourceQuotaScope]struct{})
  1169. for _, scope := range quota.Spec.Scopes {
  1170. scopes[scope] = struct{}{}
  1171. }
  1172. if _, found := scopes[api.ResourceQuotaScopeBestEffort]; !found {
  1173. framework.Failf("Expected BestEffort scope, got %v", quota.Spec.Scopes)
  1174. }
  1175. if _, found := scopes[api.ResourceQuotaScopeNotTerminating]; !found {
  1176. framework.Failf("Expected NotTerminating scope, got %v", quota.Spec.Scopes)
  1177. }
  1178. })
  1179. It("should reject quota with invalid scopes", func() {
  1180. nsFlag := fmt.Sprintf("--namespace=%v", ns)
  1181. quotaName := "scopes"
  1182. By("calling kubectl quota")
  1183. out, err := framework.RunKubectl("create", "quota", quotaName, "--hard=hard=pods=1000000", "--scopes=Foo", nsFlag)
  1184. if err == nil {
  1185. framework.Failf("Expected kubectl to fail, but it succeeded: %s", out)
  1186. }
  1187. })
  1188. })
  1189. })
  1190. // Checks whether the output split by line contains the required elements.
  1191. func checkOutput(output string, required [][]string) {
  1192. outputLines := strings.Split(output, "\n")
  1193. currentLine := 0
  1194. for _, requirement := range required {
  1195. for currentLine < len(outputLines) && !strings.Contains(outputLines[currentLine], requirement[0]) {
  1196. currentLine++
  1197. }
  1198. if currentLine == len(outputLines) {
  1199. framework.Failf("Failed to find %s in %s", requirement[0], output)
  1200. }
  1201. for _, item := range requirement[1:] {
  1202. if !strings.Contains(outputLines[currentLine], item) {
  1203. framework.Failf("Failed to find %s in %s", item, outputLines[currentLine])
  1204. }
  1205. }
  1206. }
  1207. }
  1208. func getAPIVersions(apiEndpoint string) (*unversioned.APIVersions, error) {
  1209. body, err := curl(apiEndpoint)
  1210. if err != nil {
  1211. return nil, fmt.Errorf("Failed http.Get of %s: %v", apiEndpoint, err)
  1212. }
  1213. var apiVersions unversioned.APIVersions
  1214. if err := json.Unmarshal([]byte(body), &apiVersions); err != nil {
  1215. return nil, fmt.Errorf("Failed to parse /api output %s: %v", body, err)
  1216. }
  1217. return &apiVersions, nil
  1218. }
  1219. func startProxyServer() (int, *exec.Cmd, error) {
  1220. // Specifying port 0 indicates we want the os to pick a random port.
  1221. cmd := framework.KubectlCmd("proxy", "-p", "0")
  1222. stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)
  1223. if err != nil {
  1224. return -1, nil, err
  1225. }
  1226. defer stdout.Close()
  1227. defer stderr.Close()
  1228. buf := make([]byte, 128)
  1229. var n int
  1230. if n, err = stdout.Read(buf); err != nil {
  1231. return -1, cmd, fmt.Errorf("Failed to read from kubectl proxy stdout: %v", err)
  1232. }
  1233. output := string(buf[:n])
  1234. match := proxyRegexp.FindStringSubmatch(output)
  1235. if len(match) == 2 {
  1236. if port, err := strconv.Atoi(match[1]); err == nil {
  1237. return port, cmd, nil
  1238. }
  1239. }
  1240. return -1, cmd, fmt.Errorf("Failed to parse port from proxy stdout: %s", output)
  1241. }
  1242. func curlUnix(url string, path string) (string, error) {
  1243. dial := func(proto, addr string) (net.Conn, error) {
  1244. return net.Dial("unix", path)
  1245. }
  1246. transport := utilnet.SetTransportDefaults(&http.Transport{
  1247. Dial: dial,
  1248. })
  1249. return curlTransport(url, transport)
  1250. }
  1251. func curlTransport(url string, transport *http.Transport) (string, error) {
  1252. client := &http.Client{Transport: transport}
  1253. resp, err := client.Get(url)
  1254. if err != nil {
  1255. return "", err
  1256. }
  1257. defer resp.Body.Close()
  1258. body, err := ioutil.ReadAll(resp.Body)
  1259. if err != nil {
  1260. return "", err
  1261. }
  1262. return string(body[:]), nil
  1263. }
  1264. func curl(url string) (string, error) {
  1265. return curlTransport(url, utilnet.SetTransportDefaults(&http.Transport{}))
  1266. }
  1267. func validateGuestbookApp(c *client.Client, ns string) {
  1268. framework.Logf("Waiting for all frontend pods to be Running.")
  1269. label := labels.SelectorFromSet(labels.Set(map[string]string{"tier": "frontend", "app": "guestbook"}))
  1270. err := framework.WaitForPodsWithLabelRunning(c, ns, label)
  1271. Expect(err).NotTo(HaveOccurred())
  1272. framework.Logf("Waiting for frontend to serve content.")
  1273. if !waitForGuestbookResponse(c, "get", "", `{"data": ""}`, guestbookStartupTimeout, ns) {
  1274. framework.Failf("Frontend service did not start serving content in %v seconds.", guestbookStartupTimeout.Seconds())
  1275. }
  1276. framework.Logf("Trying to add a new entry to the guestbook.")
  1277. if !waitForGuestbookResponse(c, "set", "TestEntry", `{"message": "Updated"}`, guestbookResponseTimeout, ns) {
  1278. framework.Failf("Cannot added new entry in %v seconds.", guestbookResponseTimeout.Seconds())
  1279. }
  1280. framework.Logf("Verifying that added entry can be retrieved.")
  1281. if !waitForGuestbookResponse(c, "get", "", `{"data": "TestEntry"}`, guestbookResponseTimeout, ns) {
  1282. framework.Failf("Entry to guestbook wasn't correctly added in %v seconds.", guestbookResponseTimeout.Seconds())
  1283. }
  1284. }
  1285. // Returns whether received expected response from guestbook on time.
  1286. func waitForGuestbookResponse(c *client.Client, cmd, arg, expectedResponse string, timeout time.Duration, ns string) bool {
  1287. for start := time.Now(); time.Since(start) < timeout; time.Sleep(5 * time.Second) {
  1288. res, err := makeRequestToGuestbook(c, cmd, arg, ns)
  1289. if err == nil && res == expectedResponse {
  1290. return true
  1291. }
  1292. framework.Logf("Failed to get response from guestbook. err: %v, response: %s", err, res)
  1293. }
  1294. return false
  1295. }
  1296. func makeRequestToGuestbook(c *client.Client, cmd, value string, ns string) (string, error) {
  1297. proxyRequest, errProxy := framework.GetServicesProxyRequest(c, c.Get())
  1298. if errProxy != nil {
  1299. return "", errProxy
  1300. }
  1301. result, err := proxyRequest.Namespace(ns).
  1302. Name("frontend").
  1303. Suffix("/guestbook.php").
  1304. Param("cmd", cmd).
  1305. Param("key", "messages").
  1306. Param("value", value).
  1307. Do().
  1308. Raw()
  1309. return string(result), err
  1310. }
  1311. type updateDemoData struct {
  1312. Image string
  1313. }
  1314. const applyTestLabel = "kubectl.kubernetes.io/apply-test"
  1315. func readBytesFromFile(filename string) []byte {
  1316. file, err := os.Open(filename)
  1317. if err != nil {
  1318. framework.Failf(err.Error())
  1319. }
  1320. data, err := ioutil.ReadAll(file)
  1321. if err != nil {
  1322. framework.Failf(err.Error())
  1323. }
  1324. return data
  1325. }
  1326. func readReplicationControllerFromString(contents string) *api.ReplicationController {
  1327. rc := api.ReplicationController{}
  1328. if err := yaml.Unmarshal([]byte(contents), &rc); err != nil {
  1329. framework.Failf(err.Error())
  1330. }
  1331. return &rc
  1332. }
  1333. func modifyReplicationControllerConfiguration(contents string) io.Reader {
  1334. rc := readReplicationControllerFromString(contents)
  1335. rc.Labels[applyTestLabel] = "ADDED"
  1336. rc.Spec.Selector[applyTestLabel] = "ADDED"
  1337. rc.Spec.Template.Labels[applyTestLabel] = "ADDED"
  1338. data, err := json.Marshal(rc)
  1339. if err != nil {
  1340. framework.Failf("json marshal failed: %s\n", err)
  1341. }
  1342. return bytes.NewReader(data)
  1343. }
  1344. func forEachReplicationController(c *client.Client, ns, selectorKey, selectorValue string, fn func(api.ReplicationController)) {
  1345. var rcs *api.ReplicationControllerList
  1346. var err error
  1347. for t := time.Now(); time.Since(t) < framework.PodListTimeout; time.Sleep(framework.Poll) {
  1348. label := labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue}))
  1349. options := api.ListOptions{LabelSelector: label}
  1350. rcs, err = c.ReplicationControllers(ns).List(options)
  1351. Expect(err).NotTo(HaveOccurred())
  1352. if len(rcs.Items) > 0 {
  1353. break
  1354. }
  1355. }
  1356. if rcs == nil || len(rcs.Items) == 0 {
  1357. framework.Failf("No replication controllers found")
  1358. }
  1359. for _, rc := range rcs.Items {
  1360. fn(rc)
  1361. }
  1362. }
  1363. func validateReplicationControllerConfiguration(rc api.ReplicationController) {
  1364. if rc.Name == "redis-master" {
  1365. if _, ok := rc.Annotations[annotations.LastAppliedConfigAnnotation]; !ok {
  1366. framework.Failf("Annotation not found in modified configuration:\n%v\n", rc)
  1367. }
  1368. if value, ok := rc.Labels[applyTestLabel]; !ok || value != "ADDED" {
  1369. framework.Failf("Added label %s not found in modified configuration:\n%v\n", applyTestLabel, rc)
  1370. }
  1371. }
  1372. }
  1373. // getUDData creates a validator function based on the input string (i.e. kitten.jpg).
  1374. // For example, if you send "kitten.jpg", this function verifies that the image jpg = kitten.jpg
  1375. // in the container's json field.
  1376. func getUDData(jpgExpected string, ns string) func(*client.Client, string) error {
  1377. // getUDData validates data.json in the update-demo (returns nil if data is ok).
  1378. return func(c *client.Client, podID string) error {
  1379. framework.Logf("validating pod %s", podID)
  1380. subResourceProxyAvailable, err := framework.ServerVersionGTE(framework.SubResourcePodProxyVersion, c)
  1381. if err != nil {
  1382. return err
  1383. }
  1384. var body []byte
  1385. if subResourceProxyAvailable {
  1386. body, err = c.Get().
  1387. Namespace(ns).
  1388. Resource("pods").
  1389. SubResource("proxy").
  1390. Name(podID).
  1391. Suffix("data.json").
  1392. Do().
  1393. Raw()
  1394. } else {
  1395. body, err = c.Get().
  1396. Prefix("proxy").
  1397. Namespace(ns).
  1398. Resource("pods").
  1399. Name(podID).
  1400. Suffix("data.json").
  1401. Do().
  1402. Raw()
  1403. }
  1404. if err != nil {
  1405. return err
  1406. }
  1407. framework.Logf("got data: %s", body)
  1408. var data updateDemoData
  1409. if err := json.Unmarshal(body, &data); err != nil {
  1410. return err
  1411. }
  1412. framework.Logf("Unmarshalled json jpg/img => %s , expecting %s .", data, jpgExpected)
  1413. if strings.Contains(data.Image, jpgExpected) {
  1414. return nil
  1415. } else {
  1416. return errors.New(fmt.Sprintf("data served up in container is inaccurate, %s didn't contain %s", data, jpgExpected))
  1417. }
  1418. }
  1419. }
  1420. func noOpValidatorFn(c *client.Client, podID string) error { return nil }
  1421. // newBlockingReader returns a reader that allows reading the given string,
  1422. // then blocks until Close() is called on the returned closer.
  1423. //
  1424. // We're explicitly returning the reader and closer separately, because
  1425. // the closer needs to be the *os.File we get from os.Pipe(). This is required
  1426. // so the exec of kubectl can pass the underlying file descriptor to the exec
  1427. // syscall, instead of creating another os.Pipe and blocking on the io.Copy
  1428. // between the source (e.g. stdin) and the write half of the pipe.
  1429. func newBlockingReader(s string) (io.Reader, io.Closer, error) {
  1430. r, w, err := os.Pipe()
  1431. if err != nil {
  1432. return nil, nil, err
  1433. }
  1434. w.Write([]byte(s))
  1435. return r, w, nil
  1436. }
  1437. // newStreamingUpload creates a new http.Request that will stream POST
  1438. // a file to a URI.
  1439. func newStreamingUpload(filePath string) (*io.PipeReader, *multipart.Writer, error) {
  1440. file, err := os.Open(filePath)
  1441. if err != nil {
  1442. return nil, nil, err
  1443. }
  1444. r, w := io.Pipe()
  1445. postBodyWriter := multipart.NewWriter(w)
  1446. go streamingUpload(file, filepath.Base(filePath), postBodyWriter, w)
  1447. return r, postBodyWriter, err
  1448. }
  1449. // streamingUpload streams a file via a pipe through a multipart.Writer.
  1450. // Generally one should use newStreamingUpload instead of calling this directly.
  1451. func streamingUpload(file *os.File, fileName string, postBodyWriter *multipart.Writer, w *io.PipeWriter) {
  1452. defer GinkgoRecover()
  1453. defer file.Close()
  1454. defer w.Close()
  1455. // Set up the form file
  1456. fileWriter, err := postBodyWriter.CreateFormFile("file", fileName)
  1457. if err != nil {
  1458. framework.Failf("Unable to to write file at %s to buffer. Error: %s", fileName, err)
  1459. }
  1460. // Copy kubectl binary into the file writer
  1461. if _, err := io.Copy(fileWriter, file); err != nil {
  1462. framework.Failf("Unable to to copy file at %s into the file writer. Error: %s", fileName, err)
  1463. }
  1464. // Nothing more should be written to this instance of the postBodyWriter
  1465. if err := postBodyWriter.Close(); err != nil {
  1466. framework.Failf("Unable to close the writer for file upload. Error: %s", err)
  1467. }
  1468. }
  1469. func startLocalProxy() (srv *httptest.Server, logs *bytes.Buffer) {
  1470. logs = &bytes.Buffer{}
  1471. p := goproxy.NewProxyHttpServer()
  1472. p.Verbose = true
  1473. p.Logger = log.New(logs, "", 0)
  1474. return httptest.NewServer(p), logs
  1475. }