etcd_test.go 13 KB

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