etcd_test.go 11 KB

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