etcd_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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/expect"
  24. "github.com/coreos/etcd/pkg/fileutil"
  25. "github.com/coreos/etcd/pkg/testutil"
  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 spawnWithExpect(args, expected)
  174. }
  175. func cURLGet(clus *etcdProcessCluster, key, expected string) error {
  176. return spawnWithExpect(cURLPrefixArgs(clus, key), expected)
  177. }
  178. func cURLGetUseTLS(clus *etcdProcessCluster, key, expected string) error {
  179. return spawnWithExpect(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 *expect.ExpectProcess
  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. _, err := etcdp.proc.Expect(rs)
  235. readyC <- err
  236. close(etcdp.donec)
  237. }(epc.procs[i])
  238. }
  239. for range etcdCfgs {
  240. if err := <-readyC; err != nil {
  241. epc.Close()
  242. return nil, err
  243. }
  244. }
  245. return epc, nil
  246. }
  247. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  248. if !fileutil.Exist("../bin/etcd") {
  249. return nil, fmt.Errorf("could not find etcd binary")
  250. }
  251. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  252. return nil, err
  253. }
  254. child, err := spawnCmd(append([]string{"../bin/etcd"}, cfg.args...))
  255. if err != nil {
  256. return nil, err
  257. }
  258. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  259. }
  260. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  261. clientScheme := "http"
  262. if cfg.clientTLS == clientTLS {
  263. clientScheme = "https"
  264. }
  265. peerScheme := "http"
  266. if cfg.isPeerTLS {
  267. peerScheme = "https"
  268. }
  269. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize+cfg.proxySize)
  270. initialCluster := make([]string, cfg.clusterSize)
  271. for i := 0; i < cfg.clusterSize; i++ {
  272. var curls []string
  273. var curl, curltls string
  274. port := etcdProcessBasePort + 2*i
  275. switch cfg.clientTLS {
  276. case clientNonTLS, clientTLS:
  277. curl = (&url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}).String()
  278. curls = []string{curl}
  279. case clientTLSAndNonTLS:
  280. curl = (&url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}).String()
  281. curltls = (&url.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}).String()
  282. curls = []string{curl, curltls}
  283. }
  284. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  285. name := fmt.Sprintf("testname%d", i)
  286. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  287. if derr != nil {
  288. panic("could not get tempdir for datadir")
  289. }
  290. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  291. args := []string{
  292. "--name", name,
  293. "--listen-client-urls", strings.Join(curls, ","),
  294. "--advertise-client-urls", strings.Join(curls, ","),
  295. "--listen-peer-urls", purl.String(),
  296. "--initial-advertise-peer-urls", purl.String(),
  297. "--initial-cluster-token", cfg.initialToken,
  298. "--data-dir", dataDirPath,
  299. }
  300. args = append(args, cfg.tlsArgs()...)
  301. etcdCfgs[i] = &etcdProcessConfig{
  302. args: args,
  303. dataDirPath: dataDirPath,
  304. acurl: curl,
  305. acurltls: curltls,
  306. }
  307. }
  308. for i := 0; i < cfg.proxySize; i++ {
  309. port := etcdProcessBasePort + 2*cfg.clusterSize + i + 1
  310. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  311. name := fmt.Sprintf("testname-proxy%d", i)
  312. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  313. if derr != nil {
  314. panic("could not get tempdir for datadir")
  315. }
  316. args := []string{
  317. "--name", name,
  318. "--proxy", "on",
  319. "--listen-client-urls", curl.String(),
  320. "--data-dir", dataDirPath,
  321. }
  322. args = append(args, cfg.tlsArgs()...)
  323. etcdCfgs[cfg.clusterSize+i] = &etcdProcessConfig{
  324. args: args,
  325. dataDirPath: dataDirPath,
  326. acurl: curl.String(),
  327. isProxy: true,
  328. }
  329. }
  330. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  331. for i := range etcdCfgs {
  332. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  333. }
  334. return etcdCfgs
  335. }
  336. func (cfg *etcdProcessClusterConfig) tlsArgs() (args []string) {
  337. if cfg.clientTLS != clientNonTLS {
  338. tlsClientArgs := []string{
  339. "--cert-file", certPath,
  340. "--key-file", privateKeyPath,
  341. "--ca-file", caPath,
  342. }
  343. args = append(args, tlsClientArgs...)
  344. }
  345. if cfg.isPeerTLS {
  346. if cfg.isPeerAutoTLS {
  347. args = append(args, "--peer-auto-tls=true")
  348. } else {
  349. tlsPeerArgs := []string{
  350. "--peer-cert-file", certPath,
  351. "--peer-key-file", privateKeyPath,
  352. "--peer-ca-file", caPath,
  353. }
  354. args = append(args, tlsPeerArgs...)
  355. }
  356. }
  357. return args
  358. }
  359. func (epc *etcdProcessCluster) Close() (err error) {
  360. for _, p := range epc.procs {
  361. if p == nil {
  362. continue
  363. }
  364. os.RemoveAll(p.cfg.dataDirPath)
  365. if curErr := p.proc.Stop(); curErr != nil {
  366. if err != nil {
  367. err = fmt.Errorf("%v; %v", err, curErr)
  368. } else {
  369. err = curErr
  370. }
  371. }
  372. <-p.donec
  373. }
  374. return err
  375. }
  376. func spawnCmd(args []string) (*expect.ExpectProcess, error) {
  377. // redirect stderr to stdout since expect only uses stdout
  378. cmdargs := append([]string{"-c"}, strings.Join(append(args, "2>&1"), " "))
  379. return expect.NewExpect("/bin/sh", cmdargs...)
  380. }
  381. func spawnWithExpect(args []string, expected string) error {
  382. return spawnWithExpects(args, []string{expected}...)
  383. }
  384. func spawnWithExpects(args []string, xs ...string) error {
  385. proc, err := spawnCmd(args)
  386. if err != nil {
  387. return err
  388. }
  389. for _, txt := range xs {
  390. _, err = proc.Expect(txt)
  391. if err != nil {
  392. return err
  393. }
  394. }
  395. perr := proc.Close()
  396. if err != nil {
  397. return err
  398. }
  399. return perr
  400. }
  401. // proxies returns only the proxy etcdProcess.
  402. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  403. return epc.procs[epc.cfg.clusterSize:]
  404. }
  405. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  406. return epc.procs[:epc.cfg.clusterSize]
  407. }