etcd_test.go 11 KB

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