etcd.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. "github.com/coreos/etcd/clientv3"
  25. "google.golang.org/grpc/grpclog"
  26. "k8s.io/klog"
  27. "k8s.io/kubernetes/pkg/util/env"
  28. )
  29. var etcdURL = ""
  30. const installEtcd = `
  31. Cannot find etcd, cannot run integration tests
  32. Please see https://git.k8s.io/community/contributors/devel/sig-testing/integration-tests.md#install-etcd-dependency for instructions.
  33. You can use 'hack/install-etcd.sh' to install a copy in third_party/.
  34. `
  35. // getEtcdPath returns a path to an etcd executable.
  36. func getEtcdPath() (string, error) {
  37. bazelPath := filepath.Join(os.Getenv("RUNFILES_DIR"), fmt.Sprintf("com_coreos_etcd_%s", runtime.GOARCH), "etcd")
  38. p, err := exec.LookPath(bazelPath)
  39. if err == nil {
  40. return p, nil
  41. }
  42. return exec.LookPath("etcd")
  43. }
  44. // getAvailablePort returns a TCP port that is available for binding.
  45. func getAvailablePort() (int, error) {
  46. l, err := net.Listen("tcp", ":0")
  47. if err != nil {
  48. return 0, fmt.Errorf("could not bind to a port: %v", err)
  49. }
  50. // It is possible but unlikely that someone else will bind this port before we
  51. // get a chance to use it.
  52. defer l.Close()
  53. return l.Addr().(*net.TCPAddr).Port, nil
  54. }
  55. // startEtcd executes an etcd instance. The returned function will signal the
  56. // etcd process and wait for it to exit.
  57. func startEtcd() (func(), error) {
  58. if runtime.GOARCH == "arm64" {
  59. os.Setenv("ETCD_UNSUPPORTED_ARCH", "arm64")
  60. }
  61. etcdURL = env.GetEnvAsStringOrFallback("KUBE_INTEGRATION_ETCD_URL", "http://127.0.0.1:2379")
  62. conn, err := net.Dial("tcp", strings.TrimPrefix(etcdURL, "http://"))
  63. if err == nil {
  64. klog.Infof("etcd already running at %s", etcdURL)
  65. conn.Close()
  66. return func() {}, nil
  67. }
  68. klog.V(1).Infof("could not connect to etcd: %v", err)
  69. // TODO: Check for valid etcd version.
  70. etcdPath, err := getEtcdPath()
  71. if err != nil {
  72. fmt.Fprintf(os.Stderr, installEtcd)
  73. return nil, fmt.Errorf("could not find etcd in PATH: %v", err)
  74. }
  75. etcdPort, err := getAvailablePort()
  76. if err != nil {
  77. return nil, fmt.Errorf("could not get a port: %v", err)
  78. }
  79. etcdURL = fmt.Sprintf("http://127.0.0.1:%d", etcdPort)
  80. klog.Infof("starting etcd on %s", etcdURL)
  81. etcdDataDir, err := ioutil.TempDir(os.TempDir(), "integration_test_etcd_data")
  82. if err != nil {
  83. return nil, fmt.Errorf("unable to make temp etcd data dir: %v", err)
  84. }
  85. klog.Infof("storing etcd data in: %v", etcdDataDir)
  86. ctx, cancel := context.WithCancel(context.Background())
  87. cmd := exec.CommandContext(
  88. ctx,
  89. etcdPath,
  90. "--data-dir",
  91. etcdDataDir,
  92. "--listen-client-urls",
  93. GetEtcdURL(),
  94. "--advertise-client-urls",
  95. GetEtcdURL(),
  96. "--listen-peer-urls",
  97. "http://127.0.0.1:0",
  98. "--log-package-levels",
  99. "*=NOTICE", // set to INFO or DEBUG for more logs
  100. )
  101. cmd.Stdout = os.Stdout
  102. cmd.Stderr = os.Stderr
  103. stop := func() {
  104. cancel()
  105. err := cmd.Wait()
  106. klog.Infof("etcd exit status: %v", err)
  107. err = os.RemoveAll(etcdDataDir)
  108. if err != nil {
  109. klog.Warningf("error during etcd cleanup: %v", err)
  110. }
  111. }
  112. // Quiet etcd logs for integration tests
  113. // Comment out to get verbose logs if desired
  114. clientv3.SetLogger(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, os.Stderr))
  115. if err := cmd.Start(); err != nil {
  116. return nil, fmt.Errorf("failed to run etcd: %v", err)
  117. }
  118. return stop, nil
  119. }
  120. // EtcdMain starts an etcd instance before running tests.
  121. func EtcdMain(tests func() int) {
  122. stop, err := startEtcd()
  123. if err != nil {
  124. klog.Fatalf("cannot run integration tests: unable to start etcd: %v", err)
  125. }
  126. result := tests()
  127. stop() // Don't defer this. See os.Exit documentation.
  128. os.Exit(result)
  129. }
  130. // GetEtcdURL returns the URL of the etcd instance started by EtcdMain.
  131. func GetEtcdURL() string {
  132. return etcdURL
  133. }