kubectl.go 93 KB

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