kubectl.go 98 KB

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