kubectl.go 97 KB

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