etcd_test.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. var (
  33. defaultConfig = etcdProcessClusterConfig{
  34. clusterSize: 3,
  35. proxySize: 0,
  36. isClientTLS: false,
  37. isPeerTLS: false,
  38. initialToken: "new",
  39. }
  40. defaultConfigTLS = etcdProcessClusterConfig{
  41. clusterSize: 3,
  42. proxySize: 0,
  43. isClientTLS: true,
  44. isPeerTLS: true,
  45. initialToken: "new",
  46. }
  47. defaultConfigClientTLS = etcdProcessClusterConfig{
  48. clusterSize: 3,
  49. proxySize: 0,
  50. isClientTLS: true,
  51. isPeerTLS: false,
  52. initialToken: "new",
  53. }
  54. defaultConfigPeerTLS = etcdProcessClusterConfig{
  55. clusterSize: 3,
  56. proxySize: 0,
  57. isClientTLS: false,
  58. isPeerTLS: true,
  59. initialToken: "new",
  60. }
  61. defaultConfigWithProxy = etcdProcessClusterConfig{
  62. clusterSize: 3,
  63. proxySize: 1,
  64. isClientTLS: false,
  65. isPeerTLS: false,
  66. initialToken: "new",
  67. }
  68. // TODO: this does not work now
  69. defaultConfigWithProxyTLS = etcdProcessClusterConfig{
  70. clusterSize: 3,
  71. proxySize: 1,
  72. isClientTLS: true,
  73. isPeerTLS: true,
  74. initialToken: "new",
  75. }
  76. )
  77. func TestBasicOpsNoTLS(t *testing.T) { testBasicOpsPutGet(t, &defaultConfig) }
  78. func TestBasicOpsAllTLS(t *testing.T) { testBasicOpsPutGet(t, &defaultConfigTLS) }
  79. func TestBasicOpsPeerTLS(t *testing.T) { testBasicOpsPutGet(t, &defaultConfigPeerTLS) }
  80. func TestBasicOpsClientTLS(t *testing.T) { testBasicOpsPutGet(t, &defaultConfigClientTLS) }
  81. func testBasicOpsPutGet(t *testing.T, cfg *etcdProcessClusterConfig) {
  82. defer testutil.AfterTest(t)
  83. epc, err := newEtcdProcessCluster(cfg)
  84. if err != nil {
  85. t.Fatalf("could not start etcd process cluster (%v)", err)
  86. }
  87. defer func() {
  88. if err := epc.Close(); err != nil {
  89. t.Fatalf("error closing etcd processes (%v)", err)
  90. }
  91. }()
  92. expectPut := `{"action":"set","node":{"key":"/testKey","value":"foo","`
  93. if err := cURLPut(epc, "testKey", "foo", expectPut); err != nil {
  94. t.Fatalf("failed put with curl (%v)", err)
  95. }
  96. expectGet := `{"action":"get","node":{"key":"/testKey","value":"foo","`
  97. if err := cURLGet(epc, "testKey", expectGet); err != nil {
  98. t.Fatalf("failed get with curl (%v)", err)
  99. }
  100. }
  101. // cURLPrefixArgs builds the beginning of a curl command for a given key
  102. // addressed to a random URL in the given cluster.
  103. func cURLPrefixArgs(clus *etcdProcessCluster, key string) []string {
  104. cmdArgs := []string{"curl"}
  105. if clus.cfg.isClientTLS {
  106. cmdArgs = append(cmdArgs, "--cacert", caPath, "--cert", certPath, "--key", privateKeyPath)
  107. }
  108. acurl := clus.procs[rand.Intn(clus.cfg.clusterSize)].cfg.acurl
  109. keyURL := acurl.String() + "/v2/keys/testKey"
  110. cmdArgs = append(cmdArgs, "-L", keyURL)
  111. return cmdArgs
  112. }
  113. func cURLPut(clus *etcdProcessCluster, key, val, expected string) error {
  114. args := append(cURLPrefixArgs(clus, key), "-XPUT", "-d", "value="+val)
  115. return spawnWithExpectedString(args, expected)
  116. }
  117. func cURLGet(clus *etcdProcessCluster, key, expected string) error {
  118. return spawnWithExpectedString(cURLPrefixArgs(clus, key), expected)
  119. }
  120. type etcdProcessCluster struct {
  121. cfg *etcdProcessClusterConfig
  122. procs []*etcdProcess
  123. }
  124. type etcdProcess struct {
  125. cfg *etcdProcessConfig
  126. proc *gexpect.ExpectSubprocess
  127. donec chan struct{} // closed when Interact() terminates
  128. }
  129. type etcdProcessConfig struct {
  130. args []string
  131. dataDirPath string
  132. acurl url.URL
  133. isProxy bool
  134. }
  135. type etcdProcessClusterConfig struct {
  136. clusterSize int
  137. proxySize int
  138. isClientTLS bool
  139. isPeerTLS bool
  140. initialToken string
  141. }
  142. // newEtcdProcessCluster launches a new cluster from etcd processes, returning
  143. // a new etcdProcessCluster once all nodes are ready to accept client requests.
  144. func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
  145. etcdCfgs := cfg.etcdProcessConfigs()
  146. epc := &etcdProcessCluster{
  147. cfg: cfg,
  148. procs: make([]*etcdProcess, cfg.clusterSize+cfg.proxySize),
  149. }
  150. // launch etcd processes
  151. for i := range etcdCfgs {
  152. proc, err := newEtcdProcess(etcdCfgs[i])
  153. if err != nil {
  154. epc.Close()
  155. return nil, err
  156. }
  157. epc.procs[i] = proc
  158. }
  159. // wait for cluster to start
  160. readyC := make(chan error, cfg.clusterSize+cfg.proxySize)
  161. readyStr := "etcdserver: set the initial cluster version to"
  162. for i := range etcdCfgs {
  163. go func(etcdp *etcdProcess) {
  164. rs := readyStr
  165. if etcdp.cfg.isProxy {
  166. // rs = "proxy: listening for client requests on"
  167. rs = "proxy: endpoints found"
  168. }
  169. ok, err := etcdp.proc.ExpectRegex(rs)
  170. if err != nil {
  171. readyC <- err
  172. } else if !ok {
  173. readyC <- fmt.Errorf("couldn't get expected output: '%s'", rs)
  174. } else {
  175. readyC <- nil
  176. }
  177. etcdp.proc.ReadLine()
  178. etcdp.proc.Interact() // this blocks(leaks) if another goroutine is reading
  179. etcdp.proc.ReadLine() // wait for leaky goroutine to accept an EOF
  180. close(etcdp.donec)
  181. }(epc.procs[i])
  182. }
  183. for range etcdCfgs {
  184. if err := <-readyC; err != nil {
  185. epc.Close()
  186. return nil, err
  187. }
  188. }
  189. return epc, nil
  190. }
  191. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  192. if fileutil.Exist("../bin/etcd") == false {
  193. return nil, fmt.Errorf("could not find etcd binary")
  194. }
  195. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  196. return nil, err
  197. }
  198. child, err := spawnCmd(append([]string{"../bin/etcd"}, cfg.args...))
  199. if err != nil {
  200. return nil, err
  201. }
  202. child.Capture()
  203. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  204. }
  205. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  206. clientScheme := "http"
  207. if cfg.isClientTLS {
  208. clientScheme = "https"
  209. }
  210. peerScheme := "http"
  211. if cfg.isPeerTLS {
  212. peerScheme = "https"
  213. }
  214. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize+cfg.proxySize)
  215. initialCluster := make([]string, cfg.clusterSize)
  216. for i := 0; i < cfg.clusterSize; i++ {
  217. port := etcdProcessBasePort + 2*i
  218. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  219. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  220. name := fmt.Sprintf("testname%d", i)
  221. dataDirPath := name + ".etcd"
  222. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  223. args := []string{
  224. "--name", name,
  225. "--listen-client-urls", curl.String(),
  226. "--advertise-client-urls", curl.String(),
  227. "--listen-peer-urls", purl.String(),
  228. "--initial-advertise-peer-urls", purl.String(),
  229. "--initial-cluster-token", cfg.initialToken,
  230. "--data-dir", dataDirPath,
  231. }
  232. if cfg.isClientTLS {
  233. tlsClientArgs := []string{
  234. "--cert-file", certPath,
  235. "--key-file", privateKeyPath,
  236. "--ca-file", caPath,
  237. }
  238. args = append(args, tlsClientArgs...)
  239. }
  240. if cfg.isPeerTLS {
  241. tlsPeerArgs := []string{
  242. "--peer-cert-file", certPath,
  243. "--peer-key-file", privateKeyPath,
  244. "--peer-ca-file", caPath,
  245. }
  246. args = append(args, tlsPeerArgs...)
  247. }
  248. etcdCfgs[i] = &etcdProcessConfig{
  249. args: args,
  250. dataDirPath: dataDirPath,
  251. acurl: curl,
  252. }
  253. }
  254. for i := 0; i < cfg.proxySize; i++ {
  255. port := etcdProcessBasePort + 2*cfg.clusterSize + i + 1
  256. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  257. name := fmt.Sprintf("testname-proxy%d", i)
  258. dataDirPath := name + ".etcd"
  259. args := []string{
  260. "--name", name,
  261. "--proxy", "on",
  262. "--listen-client-urls", curl.String(),
  263. "--data-dir", dataDirPath,
  264. }
  265. etcdCfgs[cfg.clusterSize+i] = &etcdProcessConfig{
  266. args: args,
  267. dataDirPath: dataDirPath,
  268. acurl: curl,
  269. isProxy: true,
  270. }
  271. }
  272. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  273. for i := range etcdCfgs {
  274. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  275. }
  276. return etcdCfgs
  277. }
  278. func (epc *etcdProcessCluster) Close() (err error) {
  279. for _, p := range epc.procs {
  280. if p == nil {
  281. continue
  282. }
  283. os.RemoveAll(p.cfg.dataDirPath)
  284. if curErr := p.proc.Close(); curErr != nil {
  285. if err != nil {
  286. err = fmt.Errorf("%v; %v", err, curErr)
  287. } else {
  288. err = curErr
  289. }
  290. }
  291. <-p.donec
  292. }
  293. return err
  294. }
  295. func spawnCmd(args []string) (*gexpect.ExpectSubprocess, error) {
  296. // redirect stderr to stdout since gexpect only uses stdout
  297. cmd := `/bin/sh -c "` + strings.Join(args, " ") + ` 2>&1 "`
  298. return gexpect.Spawn(cmd)
  299. }
  300. func spawnWithExpect(args []string, expected string) error {
  301. proc, err := spawnCmd(args)
  302. if err != nil {
  303. return err
  304. }
  305. ok, err := proc.ExpectRegex(expected)
  306. perr := proc.Close()
  307. if err != nil {
  308. return err
  309. }
  310. if !ok {
  311. return fmt.Errorf("couldn't get expected output: '%s'", expected)
  312. }
  313. return perr
  314. }
  315. // spawnWithExpectedString compares outputs in string format.
  316. // This is useful when gexpect does not match regex correctly with
  317. // some UTF-8 format characters.
  318. func spawnWithExpectedString(args []string, expected string) error {
  319. proc, err := spawnCmd(args)
  320. if err != nil {
  321. return err
  322. }
  323. s, err := proc.ReadLine()
  324. perr := proc.Close()
  325. if err != nil {
  326. return err
  327. }
  328. if !strings.Contains(s, expected) {
  329. return fmt.Errorf("expected %q, got %q", expected, s)
  330. }
  331. return perr
  332. }
  333. // proxies returns only the proxy etcdProcess.
  334. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  335. return epc.procs[epc.cfg.clusterSize:]
  336. }
  337. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  338. return epc.procs[:epc.cfg.clusterSize]
  339. }