e2e.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. Copyright 2014 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. // e2e.go runs the e2e test suite. No non-standard package dependencies; call with "go run".
  14. package main
  15. import (
  16. "flag"
  17. "fmt"
  18. "io/ioutil"
  19. "log"
  20. "os"
  21. "os/exec"
  22. "path/filepath"
  23. "strconv"
  24. "strings"
  25. "time"
  26. )
  27. var (
  28. build = flag.Bool("build", false, "If true, build a new release. Otherwise, use whatever is there.")
  29. checkNodeCount = flag.Bool("check_node_count", true, ""+
  30. "By default, verify that the cluster has at least two nodes."+
  31. "You can explicitly set to false if you're, e.g., testing single-node clusters "+
  32. "for which the node count is supposed to be one.")
  33. checkVersionSkew = flag.Bool("check_version_skew", true, ""+
  34. "By default, verify that client and server have exact version match. "+
  35. "You can explicitly set to false if you're, e.g., testing client changes "+
  36. "for which the server version doesn't make a difference.")
  37. checkLeakedResources = flag.Bool("check_leaked_resources", false, "Ensure project ends with the same resources")
  38. ctlCmd = flag.String("ctl", "", "If nonempty, pass this as an argument, and call kubectl. Implies -v.")
  39. down = flag.Bool("down", false, "If true, tear down the cluster before exiting.")
  40. dump = flag.String("dump", "", "If set, dump cluster logs to this location on test or cluster-up failure")
  41. kubemark = flag.Bool("kubemark", false, "If true, run kubemark tests.")
  42. isup = flag.Bool("isup", false, "Check to see if the e2e cluster is up, then exit.")
  43. push = flag.Bool("push", false, "If true, push to e2e cluster. Has no effect if -up is true.")
  44. pushup = flag.Bool("pushup", false, "If true, push to e2e cluster if it's up, otherwise start the e2e cluster.")
  45. skewTests = flag.Bool("skew", false, "If true, run tests in another version at ../kubernetes/hack/e2e.go")
  46. testArgs = flag.String("test_args", "", "Space-separated list of arguments to pass to Ginkgo test runner.")
  47. test = flag.Bool("test", false, "Run Ginkgo tests.")
  48. up = flag.Bool("up", false, "If true, start the the e2e cluster. If cluster is already up, recreate it.")
  49. upgradeArgs = flag.String("upgrade_args", "", "If set, run upgrade tests before other tests")
  50. verbose = flag.Bool("v", false, "If true, print all command output.")
  51. )
  52. const (
  53. minNodeCount = 2
  54. )
  55. func main() {
  56. log.SetFlags(log.LstdFlags | log.Lshortfile)
  57. flag.Parse()
  58. cwd, err := os.Getwd()
  59. if err != nil {
  60. log.Fatalf("Could not get pwd: %v", err)
  61. }
  62. acwd, err := filepath.Abs(cwd)
  63. if err != nil {
  64. log.Fatalf("Failed to convert to an absolute path: %v", err)
  65. }
  66. if !strings.Contains(filepath.Base(acwd), "kubernetes") {
  67. // TODO(fejta): cd up into the kubernetes directory
  68. log.Fatalf("Must run from kubernetes directory: %v", cwd)
  69. }
  70. if *isup {
  71. status := 1
  72. if IsUp() {
  73. status = 0
  74. log.Printf("Cluster is UP")
  75. } else {
  76. log.Printf("Cluster is DOWN")
  77. }
  78. os.Exit(status)
  79. }
  80. if *build {
  81. // The build-release script needs stdin to ask the user whether
  82. // it's OK to download the docker image.
  83. cmd := exec.Command("make", "quick-release")
  84. cmd.Stdin = os.Stdin
  85. if !finishRunning("build-release", cmd) {
  86. log.Fatal("Error building. Aborting.")
  87. }
  88. }
  89. if *up && !TearDown() {
  90. log.Fatal("Could not tear down previous cluster")
  91. }
  92. beforeResources := ""
  93. if *checkLeakedResources {
  94. beforeResources = ListResources()
  95. }
  96. os.Setenv("KUBECTL", strings.Join(append([]string{"./cluster/kubectl.sh"}, kubectlArgs()...), " "))
  97. if *upgradeArgs != "" { // Start the cluster using a previous version.
  98. if !UpgradeUp() {
  99. log.Fatal("Failed to start cluster to upgrade. Aborting.")
  100. }
  101. } else { // Start the cluster using this version.
  102. if *pushup {
  103. if IsUp() {
  104. log.Printf("e2e cluster is up, pushing.")
  105. *up = false
  106. *push = true
  107. } else {
  108. log.Printf("e2e cluster is down, creating.")
  109. *up = true
  110. *push = false
  111. }
  112. }
  113. if *up {
  114. if !Up() {
  115. DumpClusterLogs(*dump)
  116. log.Fatal("Error starting e2e cluster. Aborting.")
  117. }
  118. } else if *push {
  119. if !finishRunning("push", exec.Command("./hack/e2e-internal/e2e-push.sh")) {
  120. DumpClusterLogs(*dump)
  121. log.Fatal("Error pushing e2e cluster. Aborting.")
  122. }
  123. }
  124. }
  125. upResources := ""
  126. if *checkLeakedResources {
  127. upResources = ListResources()
  128. }
  129. success := true
  130. if *ctlCmd != "" {
  131. ctlArgs := strings.Fields(*ctlCmd)
  132. os.Setenv("KUBE_CONFIG_FILE", "config-test.sh")
  133. ctlSuccess := finishRunning("'kubectl "+*ctlCmd+"'", exec.Command("./cluster/kubectl.sh", ctlArgs...))
  134. success = success && ctlSuccess
  135. }
  136. if *upgradeArgs != "" {
  137. upgradeSuccess := UpgradeTest(*upgradeArgs)
  138. success = success && upgradeSuccess
  139. }
  140. if *test {
  141. if *skewTests {
  142. skewSuccess := SkewTest()
  143. success = success && skewSuccess
  144. } else {
  145. testSuccess := Test()
  146. success = success && testSuccess
  147. }
  148. }
  149. if *kubemark {
  150. kubeSuccess := KubemarkTest()
  151. success = success && kubeSuccess
  152. }
  153. if !success {
  154. DumpClusterLogs(*dump)
  155. }
  156. if *down {
  157. tearSuccess := TearDown()
  158. success = success && tearSuccess
  159. }
  160. if *checkLeakedResources {
  161. log.Print("Sleeping for 30 seconds...") // Wait for eventually consistent listing
  162. time.Sleep(30 * time.Second)
  163. DiffResources(beforeResources, upResources, ListResources(), *dump)
  164. }
  165. if !success {
  166. os.Exit(1)
  167. }
  168. }
  169. func writeOrDie(dir, name, data string) string {
  170. f, err := os.Create(filepath.Join(dir, name))
  171. if err != nil {
  172. log.Fatal(err)
  173. }
  174. if _, err := f.WriteString(data); err != nil {
  175. log.Fatal(err)
  176. }
  177. if err := f.Close(); err != nil {
  178. log.Fatal(err)
  179. }
  180. log.Printf("Created file: %s", f.Name())
  181. return f.Name()
  182. }
  183. func DiffResources(before, clusterUp, after, location string) {
  184. if location == "" {
  185. var err error
  186. location, err = ioutil.TempDir("", "e2e-check-resources")
  187. if err != nil {
  188. log.Fatal(err)
  189. }
  190. }
  191. bp := writeOrDie(location, "gcp-resources-before.txt", before)
  192. writeOrDie(location, "gcp-resources-cluster-up.txt", clusterUp)
  193. ap := writeOrDie(location, "gcp-resources-after.txt", after)
  194. cmd := exec.Command("diff", "-sw", "-U0", "-F^\\[.*\\]$", bp, ap)
  195. if *verbose {
  196. cmd.Stderr = os.Stderr
  197. }
  198. o, err := cmd.Output()
  199. stdout := string(o)
  200. writeOrDie(location, "gcp-resources-diff.txt", stdout)
  201. if err == nil {
  202. return
  203. }
  204. lines := strings.Split(stdout, "\n")
  205. if len(lines) < 3 { // Ignore the +++ and --- header lines
  206. return
  207. }
  208. lines = lines[2:]
  209. var added []string
  210. for _, l := range lines {
  211. if strings.HasPrefix(l, "+") && len(strings.TrimPrefix(l, "+")) > 0 {
  212. added = append(added, l)
  213. }
  214. }
  215. if len(added) > 0 {
  216. log.Printf("Error: %d leaked resources", len(added))
  217. log.Fatal(strings.Join(added, "\n"))
  218. }
  219. }
  220. func ListResources() string {
  221. log.Printf("Listing resources...")
  222. cmd := exec.Command("./cluster/gce/list-resources.sh")
  223. if *verbose {
  224. cmd.Stderr = os.Stderr
  225. }
  226. stdout, err := cmd.Output()
  227. if err != nil {
  228. log.Fatalf("Failed to list resources (%s):\n%s", err, stdout)
  229. }
  230. return string(stdout)
  231. }
  232. func TearDown() bool {
  233. return finishRunning("teardown", exec.Command("./hack/e2e-internal/e2e-down.sh"))
  234. }
  235. // Up brings an e2e cluster up, recreating it if one is already running.
  236. func Up() bool {
  237. // force having batch/v2alpha1 always on for e2e tests
  238. os.Setenv("KUBE_RUNTIME_CONFIG", "batch/v2alpha1=true")
  239. return finishRunning("up", exec.Command("./hack/e2e-internal/e2e-up.sh"))
  240. }
  241. // Ensure that the cluster is large engough to run the e2e tests.
  242. func ValidateClusterSize() {
  243. // Check that there are at least minNodeCount nodes running
  244. cmd := exec.Command("./hack/e2e-internal/e2e-cluster-size.sh")
  245. if *verbose {
  246. cmd.Stderr = os.Stderr
  247. }
  248. stdout, err := cmd.Output()
  249. if err != nil {
  250. log.Fatalf("Could not get nodes to validate cluster size (%s)", err)
  251. }
  252. numNodes, err := strconv.Atoi(strings.TrimSpace(string(stdout)))
  253. if err != nil {
  254. log.Fatalf("Could not count number of nodes to validate cluster size (%s)", err)
  255. }
  256. if numNodes < minNodeCount {
  257. log.Fatalf("Cluster size (%d) is too small to run e2e tests. %d Nodes are required.", numNodes, minNodeCount)
  258. }
  259. }
  260. // Is the e2e cluster up?
  261. func IsUp() bool {
  262. return finishRunning("get status", exec.Command("./hack/e2e-internal/e2e-status.sh"))
  263. }
  264. func DumpClusterLogs(location string) {
  265. if location == "" {
  266. return
  267. }
  268. log.Printf("Dumping cluster logs to: %v", location)
  269. finishRunning("dump cluster logs", exec.Command("./cluster/log-dump.sh", location))
  270. }
  271. func KubemarkTest() bool {
  272. // Stop previous run
  273. if !finishRunning("Stop kubemark", exec.Command("./test/kubemark/stop-kubemark.sh")) {
  274. log.Print("stop kubemark failed")
  275. return false
  276. }
  277. // Start new run
  278. backups := []string{"NUM_NODES", "MASTER_SIZE"}
  279. for _, item := range backups {
  280. old, present := os.LookupEnv(item)
  281. if present {
  282. defer os.Setenv(item, old)
  283. } else {
  284. defer os.Unsetenv(item)
  285. }
  286. }
  287. os.Setenv("NUM_NODES", os.Getenv("KUBEMARK_NUM_NODES"))
  288. os.Setenv("MASTER_SIZE", os.Getenv("KUBEMARK_MASTER_SIZE"))
  289. if !finishRunning("Start Kubemark", exec.Command("./test/kubemark/start-kubemark.sh")) {
  290. log.Print("Error: start kubemark failed")
  291. return false
  292. }
  293. // Run kubemark tests
  294. focus, present := os.LookupEnv("KUBEMARK_TESTS")
  295. if !present {
  296. focus = "starting\\s30\\pods"
  297. }
  298. test_args := os.Getenv("KUBEMARK_TEST_ARGS")
  299. if !finishRunning("Run kubemark tests", exec.Command("./test/kubemark/run-e2e-tests.sh", "--ginkgo.focus="+focus, test_args)) {
  300. log.Print("Error: run kubemark tests failed")
  301. return false
  302. }
  303. // Stop kubemark
  304. if !finishRunning("Stop kubemark", exec.Command("./test/kubemark/stop-kubemark.sh")) {
  305. log.Print("Error: stop kubemark failed")
  306. return false
  307. }
  308. return true
  309. }
  310. func UpgradeUp() bool {
  311. old, err := os.Getwd()
  312. if err != nil {
  313. log.Printf("Failed to os.Getwd(): %v", err)
  314. return false
  315. }
  316. defer os.Chdir(old)
  317. err = os.Chdir("../kubernetes_skew")
  318. if err != nil {
  319. log.Printf("Failed to cd ../kubernetes_skew: %v", err)
  320. return false
  321. }
  322. return finishRunning("UpgradeUp",
  323. exec.Command(
  324. "go", "run", "./hack/e2e.go",
  325. fmt.Sprintf("--check_version_skew=%t", *checkVersionSkew),
  326. fmt.Sprintf("--push=%t", *push),
  327. fmt.Sprintf("--pushup=%t", *pushup),
  328. fmt.Sprintf("--up=%t", *up),
  329. fmt.Sprintf("--v=%t", *verbose),
  330. ))
  331. }
  332. func UpgradeTest(args string) bool {
  333. old, err := os.Getwd()
  334. if err != nil {
  335. log.Printf("Failed to os.Getwd(): %v", err)
  336. return false
  337. }
  338. defer os.Chdir(old)
  339. err = os.Chdir("../kubernetes_skew")
  340. if err != nil {
  341. log.Printf("Failed to cd ../kubernetes_skew: %v", err)
  342. return false
  343. }
  344. previous, present := os.LookupEnv("E2E_REPORT_PREFIX")
  345. if present {
  346. defer os.Setenv("E2E_REPORT_PREFIX", previous)
  347. } else {
  348. defer os.Unsetenv("E2E_REPORT_PREFIX")
  349. }
  350. os.Setenv("E2E_REPORT_PREFIX", "upgrade")
  351. return finishRunning("Upgrade Ginkgo tests",
  352. exec.Command(
  353. "go", "run", "./hack/e2e.go",
  354. "--test",
  355. "--test_args="+args,
  356. fmt.Sprintf("--v=%t", *verbose),
  357. fmt.Sprintf("--check_version_skew=%t", *checkVersionSkew)))
  358. }
  359. func SkewTest() bool {
  360. old, err := os.Getwd()
  361. if err != nil {
  362. log.Printf("Failed to Getwd: %v", err)
  363. return false
  364. }
  365. defer os.Chdir(old)
  366. err = os.Chdir("../kubernetes_skew")
  367. if err != nil {
  368. log.Printf("Failed to cd ../kubernetes_skew: %v", err)
  369. return false
  370. }
  371. return finishRunning("Skewed Ginkgo tests",
  372. exec.Command(
  373. "go", "run", "./hack/e2e.go",
  374. "--test",
  375. "--test_args="+*testArgs,
  376. fmt.Sprintf("--v=%t", *verbose),
  377. fmt.Sprintf("--check_version_skew=%t", *checkVersionSkew)))
  378. }
  379. func Test() bool {
  380. if !IsUp() {
  381. log.Fatal("Testing requested, but e2e cluster not up!")
  382. }
  383. // TODO(fejta): add a --federated or something similar
  384. if os.Getenv("FEDERATION") == "" {
  385. if *checkNodeCount {
  386. ValidateClusterSize()
  387. }
  388. return finishRunning("Ginkgo tests", exec.Command("./hack/ginkgo-e2e.sh", strings.Fields(*testArgs)...))
  389. }
  390. if *testArgs == "" {
  391. *testArgs = "--ginkgo.focus=\\[Feature:Federation\\]"
  392. }
  393. return finishRunning("Federated Ginkgo tests", exec.Command("./hack/federated-ginkgo-e2e.sh", strings.Fields(*testArgs)...))
  394. }
  395. func finishRunning(stepName string, cmd *exec.Cmd) bool {
  396. if *verbose {
  397. cmd.Stdout = os.Stdout
  398. cmd.Stderr = os.Stderr
  399. }
  400. log.Printf("Running: %v", stepName)
  401. defer func(start time.Time) {
  402. log.Printf("Step '%s' finished in %s", stepName, time.Since(start))
  403. }(time.Now())
  404. if err := cmd.Run(); err != nil {
  405. log.Printf("Error running %v: %v", stepName, err)
  406. return false
  407. }
  408. return true
  409. }
  410. // returns either "", or a list of args intended for appending with the
  411. // kubectl command (beginning with a space).
  412. func kubectlArgs() []string {
  413. if !*checkVersionSkew {
  414. return []string{}
  415. }
  416. return []string{"--match-server-version"}
  417. }