etcd_test.go 10 KB

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