etcd_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Copyright 2016 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package e2e
  15. import (
  16. "fmt"
  17. "math/rand"
  18. "net/url"
  19. "os"
  20. "strings"
  21. "testing"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/gexpect"
  23. "github.com/coreos/etcd/pkg/fileutil"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. )
  26. const (
  27. etcdProcessBasePort = 20000
  28. certPath = "../integration/fixtures/server.crt"
  29. privateKeyPath = "../integration/fixtures/server.key.insecure"
  30. caPath = "../integration/fixtures/ca.crt"
  31. )
  32. func TestBasicOpsNoTLS(t *testing.T) {
  33. defer testutil.AfterTest(t)
  34. testProcessClusterPutGet(
  35. t,
  36. &etcdProcessClusterConfig{
  37. clusterSize: 3,
  38. isClientTLS: false,
  39. isPeerTLS: false,
  40. initialToken: "new",
  41. },
  42. )
  43. }
  44. func TestBasicOpsAllTLS(t *testing.T) {
  45. defer testutil.AfterTest(t)
  46. testProcessClusterPutGet(
  47. t,
  48. &etcdProcessClusterConfig{
  49. clusterSize: 3,
  50. isClientTLS: true,
  51. isPeerTLS: true,
  52. initialToken: "new",
  53. },
  54. )
  55. }
  56. func TestBasicOpsPeerTLS(t *testing.T) {
  57. defer testutil.AfterTest(t)
  58. testProcessClusterPutGet(
  59. t,
  60. &etcdProcessClusterConfig{
  61. clusterSize: 3,
  62. isClientTLS: false,
  63. isPeerTLS: true,
  64. initialToken: "new",
  65. },
  66. )
  67. }
  68. func TestBasicOpsClientTLS(t *testing.T) {
  69. defer testutil.AfterTest(t)
  70. testProcessClusterPutGet(
  71. t,
  72. &etcdProcessClusterConfig{
  73. clusterSize: 3,
  74. isClientTLS: true,
  75. isPeerTLS: false,
  76. initialToken: "new",
  77. },
  78. )
  79. }
  80. func testProcessClusterPutGet(t *testing.T, cfg *etcdProcessClusterConfig) {
  81. epc, err := newEtcdProcessCluster(cfg)
  82. if err != nil {
  83. t.Fatalf("could not start etcd process cluster (%v)", err)
  84. }
  85. defer func() {
  86. if err := epc.Close(); err != nil {
  87. t.Fatalf("error closing etcd processes (%v)", err)
  88. }
  89. }()
  90. expectPut := `{"action":"set","node":{"key":"/testKey","value":"foo","`
  91. if err := cURLPut(epc, "testKey", "foo", expectPut); err != nil {
  92. t.Fatalf("failed put with curl (%v)", err)
  93. }
  94. expectGet := `{"action":"get","node":{"key":"/testKey","value":"foo","`
  95. if err := cURLGet(epc, "testKey", expectGet); err != nil {
  96. t.Fatalf("failed get with curl (%v)", err)
  97. }
  98. }
  99. // cURLPrefixArgs builds the beginning of a curl command for a given key
  100. // addressed to a random URL in the given cluster.
  101. func cURLPrefixArgs(clus *etcdProcessCluster, key string) []string {
  102. cmd := []string{"curl"}
  103. if clus.cfg.isClientTLS {
  104. cmd = append(cmd, "--cacert", caPath, "--cert", certPath, "--key", privateKeyPath)
  105. }
  106. acurl := clus.procs[rand.Intn(clus.cfg.clusterSize)].cfg.acurl
  107. keyURL := acurl.String() + "/v2/keys/testKey"
  108. cmd = append(cmd, "-L", keyURL)
  109. return cmd
  110. }
  111. func cURLPut(clus *etcdProcessCluster, key, val, expected string) error {
  112. args := append(cURLPrefixArgs(clus, key), "-XPUT", "-d", "value="+val)
  113. return spawnWithExpect(args, expected)
  114. }
  115. func cURLGet(clus *etcdProcessCluster, key, expected string) error {
  116. return spawnWithExpect(cURLPrefixArgs(clus, key), expected)
  117. }
  118. type etcdProcessCluster struct {
  119. cfg *etcdProcessClusterConfig
  120. procs []*etcdProcess
  121. }
  122. type etcdProcess struct {
  123. cfg *etcdProcessConfig
  124. proc *gexpect.ExpectSubprocess
  125. donec chan struct{} // closed when Interact() terminates
  126. }
  127. type etcdProcessConfig struct {
  128. args []string
  129. dataDirPath string
  130. acurl url.URL
  131. }
  132. type etcdProcessClusterConfig struct {
  133. clusterSize int
  134. isClientTLS bool
  135. isPeerTLS bool
  136. initialToken string
  137. }
  138. // newEtcdProcessCluster launches a new cluster from etcd processes, returning
  139. // a new etcdProcessCluster once all nodes are ready to accept client requests.
  140. func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
  141. etcdCfgs := cfg.etcdProcessConfigs()
  142. epc := &etcdProcessCluster{
  143. cfg: cfg,
  144. procs: make([]*etcdProcess, cfg.clusterSize),
  145. }
  146. // launch etcd processes
  147. for i := range etcdCfgs {
  148. proc, err := newEtcdProcess(etcdCfgs[i])
  149. if err != nil {
  150. epc.Close()
  151. return nil, err
  152. }
  153. epc.procs[i] = proc
  154. }
  155. // wait for cluster to start
  156. readyC := make(chan error, cfg.clusterSize)
  157. readyStr := "set the initial cluster version"
  158. for i := range etcdCfgs {
  159. go func(etcdp *etcdProcess) {
  160. _, err := etcdp.proc.ExpectRegex(readyStr)
  161. readyC <- err
  162. etcdp.proc.ReadLine()
  163. etcdp.proc.Interact() // this blocks(leaks) if another goroutine is reading
  164. etcdp.proc.ReadLine() // wait for leaky goroutine to accept an EOF
  165. close(etcdp.donec)
  166. }(epc.procs[i])
  167. }
  168. for range etcdCfgs {
  169. if err := <-readyC; err != nil {
  170. epc.Close()
  171. return nil, err
  172. }
  173. }
  174. return epc, nil
  175. }
  176. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  177. if fileutil.Exist("../bin/etcd") == false {
  178. return nil, fmt.Errorf("could not find etcd binary")
  179. }
  180. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  181. return nil, err
  182. }
  183. child, err := spawnCmd(append([]string{"../bin/etcd"}, cfg.args...))
  184. if err != nil {
  185. return nil, err
  186. }
  187. child.Capture()
  188. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  189. }
  190. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  191. clientScheme := "http"
  192. if cfg.isClientTLS {
  193. clientScheme = "https"
  194. }
  195. peerScheme := "http"
  196. if cfg.isPeerTLS {
  197. peerScheme = "https"
  198. }
  199. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize)
  200. initialCluster := make([]string, cfg.clusterSize)
  201. for i := 0; i < cfg.clusterSize; i++ {
  202. port := etcdProcessBasePort + 2*i
  203. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  204. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  205. name := fmt.Sprintf("testname%d", i)
  206. dataDirPath := name + ".etcd"
  207. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  208. args := []string{
  209. "--name", name,
  210. "--listen-client-urls", curl.String(),
  211. "--advertise-client-urls", curl.String(),
  212. "--listen-peer-urls", purl.String(),
  213. "--initial-advertise-peer-urls", purl.String(),
  214. "--initial-cluster-token", cfg.initialToken,
  215. "--data-dir", dataDirPath,
  216. }
  217. if cfg.isClientTLS {
  218. tlsClientArgs := []string{
  219. "--cert-file", certPath,
  220. "--key-file", privateKeyPath,
  221. "--ca-file", caPath,
  222. }
  223. args = append(args, tlsClientArgs...)
  224. }
  225. if cfg.isPeerTLS {
  226. tlsPeerArgs := []string{
  227. "--peer-cert-file", certPath,
  228. "--peer-key-file", privateKeyPath,
  229. "--peer-ca-file", caPath,
  230. }
  231. args = append(args, tlsPeerArgs...)
  232. }
  233. etcdCfgs[i] = &etcdProcessConfig{
  234. args: args,
  235. dataDirPath: dataDirPath,
  236. acurl: curl,
  237. }
  238. }
  239. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  240. for i := range etcdCfgs {
  241. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  242. }
  243. return etcdCfgs
  244. }
  245. func (epc *etcdProcessCluster) Close() (err error) {
  246. for _, p := range epc.procs {
  247. if p == nil {
  248. continue
  249. }
  250. os.RemoveAll(p.cfg.dataDirPath)
  251. if curErr := p.proc.Close(); curErr != nil {
  252. if err != nil {
  253. err = fmt.Errorf("%v; %v", err, curErr)
  254. } else {
  255. err = curErr
  256. }
  257. }
  258. <-p.donec
  259. }
  260. return err
  261. }
  262. func spawnCmd(args []string) (*gexpect.ExpectSubprocess, error) {
  263. // redirect stderr to stdout since gexpect only uses stdout
  264. cmd := `/bin/sh -c "` + strings.Join(args, " ") + ` 2>&1 "`
  265. return gexpect.Spawn(cmd)
  266. }
  267. func spawnWithExpect(args []string, expected string) error {
  268. proc, err := spawnCmd(args)
  269. if err != nil {
  270. return err
  271. }
  272. if _, err := proc.ExpectRegex(expected); err != nil {
  273. return err
  274. }
  275. return proc.Close()
  276. }