etcd_test.go 11 KB

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