etcd_test.go 11 KB

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