etcd.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package framework
  14. import (
  15. "context"
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "runtime"
  23. "strings"
  24. "time"
  25. "go.etcd.io/etcd/clientv3"
  26. "google.golang.org/grpc/grpclog"
  27. "k8s.io/klog"
  28. "k8s.io/kubernetes/pkg/util/env"
  29. )
  30. var etcdURL = ""
  31. const installEtcd = `
  32. Cannot find etcd, cannot run integration tests
  33. Please see https://git.k8s.io/community/contributors/devel/sig-testing/integration-tests.md#install-etcd-dependency for instructions.
  34. You can use 'hack/install-etcd.sh' to install a copy in third_party/.
  35. `
  36. // getEtcdPath returns a path to an etcd executable.
  37. func getEtcdPath() (string, error) {
  38. bazelPath := filepath.Join(os.Getenv("RUNFILES_DIR"), fmt.Sprintf("com_coreos_etcd_%s", runtime.GOARCH), "etcd")
  39. p, err := exec.LookPath(bazelPath)
  40. if err == nil {
  41. return p, nil
  42. }
  43. return exec.LookPath("etcd")
  44. }
  45. // getAvailablePort returns a TCP port that is available for binding.
  46. func getAvailablePort() (int, error) {
  47. l, err := net.Listen("tcp", ":0")
  48. if err != nil {
  49. return 0, fmt.Errorf("could not bind to a port: %v", err)
  50. }
  51. // It is possible but unlikely that someone else will bind this port before we
  52. // get a chance to use it.
  53. defer l.Close()
  54. return l.Addr().(*net.TCPAddr).Port, nil
  55. }
  56. // startEtcd executes an etcd instance. The returned function will signal the
  57. // etcd process and wait for it to exit.
  58. func startEtcd() (func(), error) {
  59. if runtime.GOARCH == "arm64" {
  60. os.Setenv("ETCD_UNSUPPORTED_ARCH", "arm64")
  61. }
  62. etcdURL = env.GetEnvAsStringOrFallback("KUBE_INTEGRATION_ETCD_URL", "http://127.0.0.1:2379")
  63. conn, err := net.Dial("tcp", strings.TrimPrefix(etcdURL, "http://"))
  64. if err == nil {
  65. klog.Infof("etcd already running at %s", etcdURL)
  66. conn.Close()
  67. return func() {}, nil
  68. }
  69. klog.V(1).Infof("could not connect to etcd: %v", err)
  70. // TODO: Check for valid etcd version.
  71. etcdPath, err := getEtcdPath()
  72. if err != nil {
  73. fmt.Fprintf(os.Stderr, installEtcd)
  74. return nil, fmt.Errorf("could not find etcd in PATH: %v", err)
  75. }
  76. etcdPort, err := getAvailablePort()
  77. if err != nil {
  78. return nil, fmt.Errorf("could not get a port: %v", err)
  79. }
  80. etcdURL = fmt.Sprintf("http://127.0.0.1:%d", etcdPort)
  81. klog.Infof("starting etcd on %s", etcdURL)
  82. etcdDataDir, err := ioutil.TempDir(os.TempDir(), "integration_test_etcd_data")
  83. if err != nil {
  84. return nil, fmt.Errorf("unable to make temp etcd data dir: %v", err)
  85. }
  86. klog.Infof("storing etcd data in: %v", etcdDataDir)
  87. ctx, cancel := context.WithCancel(context.Background())
  88. cmd := exec.CommandContext(
  89. ctx,
  90. etcdPath,
  91. "--data-dir",
  92. etcdDataDir,
  93. "--listen-client-urls",
  94. GetEtcdURL(),
  95. "--advertise-client-urls",
  96. GetEtcdURL(),
  97. "--listen-peer-urls",
  98. "http://127.0.0.1:0",
  99. "--log-package-levels",
  100. "*=NOTICE", // set to INFO or DEBUG for more logs
  101. )
  102. cmd.Stdout = os.Stdout
  103. cmd.Stderr = os.Stderr
  104. stop := func() {
  105. cancel()
  106. err := cmd.Wait()
  107. klog.Infof("etcd exit status: %v", err)
  108. err = os.RemoveAll(etcdDataDir)
  109. if err != nil {
  110. klog.Warningf("error during etcd cleanup: %v", err)
  111. }
  112. }
  113. // Quiet etcd logs for integration tests
  114. // Comment out to get verbose logs if desired
  115. clientv3.SetLogger(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, os.Stderr))
  116. if err := cmd.Start(); err != nil {
  117. return nil, fmt.Errorf("failed to run etcd: %v", err)
  118. }
  119. var i int32 = 1
  120. const pollCount = int32(300)
  121. for i <= pollCount {
  122. conn, err = net.DialTimeout("tcp", strings.TrimPrefix(etcdURL, "http://"), 1*time.Second)
  123. if err == nil {
  124. conn.Close()
  125. break
  126. }
  127. if i == pollCount {
  128. stop()
  129. return nil, fmt.Errorf("could not start etcd")
  130. }
  131. time.Sleep(100 * time.Millisecond)
  132. i = i + 1
  133. }
  134. os.Setenv("KUBE_INTEGRATION_ETCD_URL", etcdURL)
  135. return stop, nil
  136. }
  137. // EtcdMain starts an etcd instance before running tests.
  138. func EtcdMain(tests func() int) {
  139. stop, err := startEtcd()
  140. if err != nil {
  141. klog.Fatalf("cannot run integration tests: unable to start etcd: %v", err)
  142. }
  143. result := tests()
  144. stop() // Don't defer this. See os.Exit documentation.
  145. os.Exit(result)
  146. }
  147. // GetEtcdURL returns the URL of the etcd instance started by EtcdMain.
  148. func GetEtcdURL() string {
  149. return etcdURL
  150. }