etcd_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. "io/ioutil"
  18. "math/rand"
  19. "net/url"
  20. "os"
  21. "strings"
  22. "testing"
  23. "github.com/coreos/etcd/pkg/fileutil"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. "github.com/coreos/gexpect"
  26. )
  27. const (
  28. etcdProcessBasePort = 20000
  29. certPath = "../integration/fixtures/server.crt"
  30. privateKeyPath = "../integration/fixtures/server.key.insecure"
  31. caPath = "../integration/fixtures/ca.crt"
  32. )
  33. var (
  34. configNoTLS = etcdProcessClusterConfig{
  35. clusterSize: 3,
  36. proxySize: 0,
  37. isClientTLS: false,
  38. isPeerTLS: false,
  39. initialToken: "new",
  40. }
  41. configAutoTLS = etcdProcessClusterConfig{
  42. clusterSize: 3,
  43. isPeerTLS: true,
  44. isPeerAutoTLS: true,
  45. initialToken: "new",
  46. }
  47. configTLS = etcdProcessClusterConfig{
  48. clusterSize: 3,
  49. proxySize: 0,
  50. isClientTLS: true,
  51. isPeerTLS: true,
  52. initialToken: "new",
  53. }
  54. configClientTLS = etcdProcessClusterConfig{
  55. clusterSize: 3,
  56. proxySize: 0,
  57. isClientTLS: true,
  58. isPeerTLS: false,
  59. initialToken: "new",
  60. }
  61. configClientBoth = etcdProcessClusterConfig{
  62. clusterSize: 1,
  63. proxySize: 0,
  64. isClientBoth: true,
  65. isPeerTLS: false,
  66. initialToken: "new",
  67. }
  68. configPeerTLS = etcdProcessClusterConfig{
  69. clusterSize: 3,
  70. proxySize: 0,
  71. isClientTLS: false,
  72. isPeerTLS: true,
  73. initialToken: "new",
  74. }
  75. configWithProxy = etcdProcessClusterConfig{
  76. clusterSize: 3,
  77. proxySize: 1,
  78. isClientTLS: false,
  79. isPeerTLS: false,
  80. initialToken: "new",
  81. }
  82. configWithProxyTLS = etcdProcessClusterConfig{
  83. clusterSize: 3,
  84. proxySize: 1,
  85. isClientTLS: true,
  86. isPeerTLS: true,
  87. initialToken: "new",
  88. }
  89. configWithProxyPeerTLS = etcdProcessClusterConfig{
  90. clusterSize: 3,
  91. proxySize: 1,
  92. isClientTLS: false,
  93. isPeerTLS: true,
  94. initialToken: "new",
  95. }
  96. )
  97. func configStandalone(cfg etcdProcessClusterConfig) *etcdProcessClusterConfig {
  98. ret := cfg
  99. ret.clusterSize = 1
  100. return &ret
  101. }
  102. func TestBasicOpsNoTLS(t *testing.T) { testBasicOpsPutGet(t, &configNoTLS) }
  103. func TestBasicOpsAutoTLS(t *testing.T) { testBasicOpsPutGet(t, &configAutoTLS) }
  104. func TestBasicOpsAllTLS(t *testing.T) { testBasicOpsPutGet(t, &configTLS) }
  105. func TestBasicOpsPeerTLS(t *testing.T) { testBasicOpsPutGet(t, &configPeerTLS) }
  106. func TestBasicOpsClientTLS(t *testing.T) { testBasicOpsPutGet(t, &configClientTLS) }
  107. func TestBasicOpsProxyNoTLS(t *testing.T) { testBasicOpsPutGet(t, &configWithProxy) }
  108. func TestBasicOpsProxyTLS(t *testing.T) { testBasicOpsPutGet(t, &configWithProxyTLS) }
  109. func TestBasicOpsProxyPeerTLS(t *testing.T) { testBasicOpsPutGet(t, &configWithProxyPeerTLS) }
  110. func TestBasicOpsClientBoth(t *testing.T) { testBasicOpsPutGet(t, &configClientBoth) }
  111. func testBasicOpsPutGet(t *testing.T, cfg *etcdProcessClusterConfig) {
  112. defer testutil.AfterTest(t)
  113. // test doesn't use quorum gets, so ensure there are no followers to avoid
  114. // stale reads that will break the test
  115. cfg = configStandalone(*cfg)
  116. epc, err := newEtcdProcessCluster(cfg)
  117. if err != nil {
  118. t.Fatalf("could not start etcd process cluster (%v)", err)
  119. }
  120. defer func() {
  121. if err := epc.Close(); err != nil {
  122. t.Fatalf("error closing etcd processes (%v)", err)
  123. }
  124. }()
  125. expectPut := `{"action":"set","node":{"key":"/testKey","value":"foo","`
  126. expectGet := `{"action":"get","node":{"key":"/testKey","value":"foo","`
  127. if cfg.isClientBoth {
  128. if err := cURLPut(epc, "testKey", "foo", expectPut); err != nil {
  129. t.Fatalf("failed put with curl (%v)", err)
  130. }
  131. if err := cURLGet(epc, "testKey", expectGet); err != nil {
  132. t.Fatalf("failed get with curl (%v)", err)
  133. }
  134. if err := cURLGetUseTLS(epc, "testKey", expectGet); err != nil {
  135. t.Fatalf("failed get with curl (%v)", err)
  136. }
  137. } else {
  138. if err := cURLPut(epc, "testKey", "foo", expectPut); err != nil {
  139. t.Fatalf("failed put with curl (%v)", err)
  140. }
  141. if err := cURLGet(epc, "testKey", expectGet); err != nil {
  142. t.Fatalf("failed get with curl (%v)", err)
  143. }
  144. }
  145. }
  146. // cURLPrefixArgs builds the beginning of a curl command for a given key
  147. // addressed to a random URL in the given cluster.
  148. func cURLPrefixArgs(clus *etcdProcessCluster, key string) []string {
  149. cmdArgs := []string{"curl"}
  150. if clus.cfg.isClientTLS {
  151. cmdArgs = append(cmdArgs, "--cacert", caPath, "--cert", certPath, "--key", privateKeyPath)
  152. }
  153. acurl := clus.procs[rand.Intn(clus.cfg.clusterSize)].cfg.acurl[0]
  154. keyURL := acurl + "/v2/keys/testKey"
  155. cmdArgs = append(cmdArgs, "-L", keyURL)
  156. return cmdArgs
  157. }
  158. func cURLPrefixArgsUseTLS(clus *etcdProcessCluster, key string) []string {
  159. cmdArgs := []string{"curl"}
  160. if !clus.cfg.isClientBoth {
  161. panic("should not use cURLPrefixArgsUseTLS when serving only TLS or non-TLS")
  162. }
  163. cmdArgs = append(cmdArgs, "--cacert", caPath, "--cert", certPath, "--key", privateKeyPath)
  164. acurl := clus.procs[rand.Intn(clus.cfg.clusterSize)].cfg.acurl[1]
  165. keyURL := acurl + "/v2/keys/testKey"
  166. cmdArgs = append(cmdArgs, "-L", keyURL)
  167. return cmdArgs
  168. }
  169. func cURLPut(clus *etcdProcessCluster, key, val, expected string) error {
  170. args := append(cURLPrefixArgs(clus, key), "-XPUT", "-d", "value="+val)
  171. return spawnWithExpectedString(args, expected)
  172. }
  173. func cURLGet(clus *etcdProcessCluster, key, expected string) error {
  174. return spawnWithExpectedString(cURLPrefixArgs(clus, key), expected)
  175. }
  176. func cURLGetUseTLS(clus *etcdProcessCluster, key, expected string) error {
  177. return spawnWithExpectedString(cURLPrefixArgsUseTLS(clus, key), expected)
  178. }
  179. type etcdProcessCluster struct {
  180. cfg *etcdProcessClusterConfig
  181. procs []*etcdProcess
  182. }
  183. type etcdProcess struct {
  184. cfg *etcdProcessConfig
  185. proc *gexpect.ExpectSubprocess
  186. donec chan struct{} // closed when Interact() terminates
  187. }
  188. type etcdProcessConfig struct {
  189. args []string
  190. dataDirPath string
  191. acurl []string
  192. isProxy bool
  193. }
  194. type etcdProcessClusterConfig struct {
  195. clusterSize int
  196. proxySize int
  197. isClientTLS bool
  198. // serve both TLS and non-TLS
  199. isClientBoth bool
  200. isPeerTLS bool
  201. isPeerAutoTLS bool
  202. initialToken string
  203. isV3 bool
  204. }
  205. // newEtcdProcessCluster launches a new cluster from etcd processes, returning
  206. // a new etcdProcessCluster once all nodes are ready to accept client requests.
  207. func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
  208. etcdCfgs := cfg.etcdProcessConfigs()
  209. epc := &etcdProcessCluster{
  210. cfg: cfg,
  211. procs: make([]*etcdProcess, cfg.clusterSize+cfg.proxySize),
  212. }
  213. // launch etcd processes
  214. for i := range etcdCfgs {
  215. proc, err := newEtcdProcess(etcdCfgs[i])
  216. if err != nil {
  217. epc.Close()
  218. return nil, err
  219. }
  220. epc.procs[i] = proc
  221. }
  222. // wait for cluster to start
  223. readyC := make(chan error, cfg.clusterSize+cfg.proxySize)
  224. readyStr := "etcdserver: set the initial cluster version to"
  225. for i := range etcdCfgs {
  226. go func(etcdp *etcdProcess) {
  227. rs := readyStr
  228. if etcdp.cfg.isProxy {
  229. // rs = "proxy: listening for client requests on"
  230. rs = "proxy: endpoints found"
  231. }
  232. ok, err := etcdp.proc.ExpectRegex(rs)
  233. if err != nil {
  234. readyC <- err
  235. } else if !ok {
  236. readyC <- fmt.Errorf("couldn't get expected output: '%s'", rs)
  237. } else {
  238. readyC <- nil
  239. }
  240. etcdp.proc.ReadLine()
  241. etcdp.proc.Interact() // this blocks(leaks) if another goroutine is reading
  242. etcdp.proc.ReadLine() // wait for leaky goroutine to accept an EOF
  243. close(etcdp.donec)
  244. }(epc.procs[i])
  245. }
  246. for range etcdCfgs {
  247. if err := <-readyC; err != nil {
  248. epc.Close()
  249. return nil, err
  250. }
  251. }
  252. return epc, nil
  253. }
  254. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  255. if fileutil.Exist("../bin/etcd") == false {
  256. return nil, fmt.Errorf("could not find etcd binary")
  257. }
  258. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  259. return nil, err
  260. }
  261. child, err := spawnCmd(append([]string{"../bin/etcd"}, cfg.args...))
  262. if err != nil {
  263. return nil, err
  264. }
  265. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  266. }
  267. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  268. clientScheme := "http"
  269. if cfg.isClientTLS {
  270. clientScheme = "https"
  271. }
  272. peerScheme := "http"
  273. if cfg.isPeerTLS {
  274. peerScheme = "https"
  275. }
  276. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize+cfg.proxySize)
  277. initialCluster := make([]string, cfg.clusterSize)
  278. for i := 0; i < cfg.clusterSize; i++ {
  279. var curlstrs []string
  280. port := etcdProcessBasePort + 2*i
  281. if !cfg.isClientBoth {
  282. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  283. curlstrs = []string{curl.String()}
  284. } else {
  285. curl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}
  286. curltls := url.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
  287. curlstrs = []string{curl.String(), curltls.String()}
  288. }
  289. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  290. name := fmt.Sprintf("testname%d", i)
  291. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  292. if derr != nil {
  293. panic("could not get tempdir for datadir")
  294. }
  295. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  296. args := []string{
  297. "--name", name,
  298. "--listen-client-urls", strings.Join(curlstrs, ","),
  299. "--advertise-client-urls", strings.Join(curlstrs, ","),
  300. "--listen-peer-urls", purl.String(),
  301. "--initial-advertise-peer-urls", purl.String(),
  302. "--initial-cluster-token", cfg.initialToken,
  303. "--data-dir", dataDirPath,
  304. }
  305. if cfg.isV3 {
  306. args = append(args, "--experimental-v3demo")
  307. }
  308. args = append(args, cfg.tlsArgs()...)
  309. etcdCfgs[i] = &etcdProcessConfig{
  310. args: args,
  311. dataDirPath: dataDirPath,
  312. acurl: curlstrs,
  313. }
  314. }
  315. for i := 0; i < cfg.proxySize; i++ {
  316. port := etcdProcessBasePort + 2*cfg.clusterSize + i + 1
  317. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  318. name := fmt.Sprintf("testname-proxy%d", i)
  319. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  320. if derr != nil {
  321. panic("could not get tempdir for datadir")
  322. }
  323. args := []string{
  324. "--name", name,
  325. "--proxy", "on",
  326. "--listen-client-urls", curl.String(),
  327. "--data-dir", dataDirPath,
  328. }
  329. args = append(args, cfg.tlsArgs()...)
  330. etcdCfgs[cfg.clusterSize+i] = &etcdProcessConfig{
  331. args: args,
  332. dataDirPath: dataDirPath,
  333. acurl: []string{curl.String()},
  334. isProxy: true,
  335. }
  336. }
  337. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  338. for i := range etcdCfgs {
  339. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  340. }
  341. return etcdCfgs
  342. }
  343. func (cfg *etcdProcessClusterConfig) tlsArgs() (args []string) {
  344. if cfg.isClientTLS || cfg.isClientBoth {
  345. tlsClientArgs := []string{
  346. "--cert-file", certPath,
  347. "--key-file", privateKeyPath,
  348. "--ca-file", caPath,
  349. }
  350. args = append(args, tlsClientArgs...)
  351. }
  352. if cfg.isPeerTLS {
  353. if cfg.isPeerAutoTLS {
  354. args = append(args, "--peer-auto-tls=true")
  355. } else {
  356. tlsPeerArgs := []string{
  357. "--peer-cert-file", certPath,
  358. "--peer-key-file", privateKeyPath,
  359. "--peer-ca-file", caPath,
  360. }
  361. args = append(args, tlsPeerArgs...)
  362. }
  363. }
  364. return args
  365. }
  366. func (epc *etcdProcessCluster) Close() (err error) {
  367. for _, p := range epc.procs {
  368. if p == nil {
  369. continue
  370. }
  371. os.RemoveAll(p.cfg.dataDirPath)
  372. if curErr := p.proc.Close(); curErr != nil {
  373. if err != nil {
  374. err = fmt.Errorf("%v; %v", err, curErr)
  375. } else {
  376. err = curErr
  377. }
  378. }
  379. <-p.donec
  380. }
  381. return err
  382. }
  383. func spawnCmd(args []string) (*gexpect.ExpectSubprocess, error) {
  384. // redirect stderr to stdout since gexpect only uses stdout
  385. cmd := `/bin/sh -c "` + strings.Join(args, " ") + ` 2>&1 "`
  386. return gexpect.Spawn(cmd)
  387. }
  388. func spawnWithExpect(args []string, expected string) error {
  389. proc, err := spawnCmd(args)
  390. if err != nil {
  391. return err
  392. }
  393. ok, err := proc.ExpectRegex(expected)
  394. perr := proc.Close()
  395. if err != nil {
  396. return err
  397. }
  398. if !ok {
  399. return fmt.Errorf("couldn't get expected output: '%s'", expected)
  400. }
  401. return perr
  402. }
  403. // spawnWithExpectedString compares outputs in string format.
  404. // This is useful when gexpect does not match regex correctly with
  405. // some UTF-8 format characters.
  406. func spawnWithExpectedString(args []string, expected string) error {
  407. proc, err := spawnCmd(args)
  408. if err != nil {
  409. return err
  410. }
  411. s, err := proc.ReadLine()
  412. perr := proc.Close()
  413. if err != nil {
  414. return err
  415. }
  416. if !strings.Contains(s, expected) {
  417. return fmt.Errorf("expected %q, got %q", expected, s)
  418. }
  419. return perr
  420. }
  421. // proxies returns only the proxy etcdProcess.
  422. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  423. return epc.procs[epc.cfg.clusterSize:]
  424. }
  425. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  426. return epc.procs[:epc.cfg.clusterSize]
  427. }