etcd_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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/fileutil"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. "github.com/coreos/gexpect"
  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. isV3 bool
  168. }
  169. // newEtcdProcessCluster launches a new cluster from etcd processes, returning
  170. // a new etcdProcessCluster once all nodes are ready to accept client requests.
  171. func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
  172. etcdCfgs := cfg.etcdProcessConfigs()
  173. epc := &etcdProcessCluster{
  174. cfg: cfg,
  175. procs: make([]*etcdProcess, cfg.clusterSize+cfg.proxySize),
  176. }
  177. // launch etcd processes
  178. for i := range etcdCfgs {
  179. proc, err := newEtcdProcess(etcdCfgs[i])
  180. if err != nil {
  181. epc.Close()
  182. return nil, err
  183. }
  184. epc.procs[i] = proc
  185. }
  186. // wait for cluster to start
  187. readyC := make(chan error, cfg.clusterSize+cfg.proxySize)
  188. readyStr := "etcdserver: set the initial cluster version to"
  189. for i := range etcdCfgs {
  190. go func(etcdp *etcdProcess) {
  191. rs := readyStr
  192. if etcdp.cfg.isProxy {
  193. // rs = "proxy: listening for client requests on"
  194. rs = "proxy: endpoints found"
  195. }
  196. ok, err := etcdp.proc.ExpectRegex(rs)
  197. if err != nil {
  198. readyC <- err
  199. } else if !ok {
  200. readyC <- fmt.Errorf("couldn't get expected output: '%s'", rs)
  201. } else {
  202. readyC <- nil
  203. }
  204. etcdp.proc.ReadLine()
  205. etcdp.proc.Interact() // this blocks(leaks) if another goroutine is reading
  206. etcdp.proc.ReadLine() // wait for leaky goroutine to accept an EOF
  207. close(etcdp.donec)
  208. }(epc.procs[i])
  209. }
  210. for range etcdCfgs {
  211. if err := <-readyC; err != nil {
  212. epc.Close()
  213. return nil, err
  214. }
  215. }
  216. return epc, nil
  217. }
  218. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  219. if fileutil.Exist("../bin/etcd") == false {
  220. return nil, fmt.Errorf("could not find etcd binary")
  221. }
  222. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  223. return nil, err
  224. }
  225. child, err := spawnCmd(append([]string{"../bin/etcd"}, cfg.args...))
  226. if err != nil {
  227. return nil, err
  228. }
  229. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  230. }
  231. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  232. clientScheme := "http"
  233. if cfg.isClientTLS {
  234. clientScheme = "https"
  235. }
  236. peerScheme := "http"
  237. if cfg.isPeerTLS {
  238. peerScheme = "https"
  239. }
  240. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize+cfg.proxySize)
  241. initialCluster := make([]string, cfg.clusterSize)
  242. for i := 0; i < cfg.clusterSize; i++ {
  243. port := etcdProcessBasePort + 2*i
  244. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  245. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  246. name := fmt.Sprintf("testname%d", i)
  247. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  248. if derr != nil {
  249. panic("could not get tempdir for datadir")
  250. }
  251. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  252. args := []string{
  253. "--name", name,
  254. "--listen-client-urls", curl.String(),
  255. "--advertise-client-urls", curl.String(),
  256. "--listen-peer-urls", purl.String(),
  257. "--initial-advertise-peer-urls", purl.String(),
  258. "--initial-cluster-token", cfg.initialToken,
  259. "--data-dir", dataDirPath,
  260. }
  261. if cfg.isV3 {
  262. args = append(args, "--experimental-v3demo")
  263. }
  264. args = append(args, cfg.tlsArgs()...)
  265. etcdCfgs[i] = &etcdProcessConfig{
  266. args: args,
  267. dataDirPath: dataDirPath,
  268. acurl: curl,
  269. }
  270. }
  271. for i := 0; i < cfg.proxySize; i++ {
  272. port := etcdProcessBasePort + 2*cfg.clusterSize + i + 1
  273. curl := url.URL{Scheme: clientScheme, Host: fmt.Sprintf("localhost:%d", port)}
  274. name := fmt.Sprintf("testname-proxy%d", i)
  275. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  276. if derr != nil {
  277. panic("could not get tempdir for datadir")
  278. }
  279. args := []string{
  280. "--name", name,
  281. "--proxy", "on",
  282. "--listen-client-urls", curl.String(),
  283. "--data-dir", dataDirPath,
  284. }
  285. args = append(args, cfg.tlsArgs()...)
  286. etcdCfgs[cfg.clusterSize+i] = &etcdProcessConfig{
  287. args: args,
  288. dataDirPath: dataDirPath,
  289. acurl: curl,
  290. isProxy: true,
  291. }
  292. }
  293. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  294. for i := range etcdCfgs {
  295. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  296. }
  297. return etcdCfgs
  298. }
  299. func (cfg *etcdProcessClusterConfig) tlsArgs() (args []string) {
  300. if cfg.isClientTLS {
  301. tlsClientArgs := []string{
  302. "--cert-file", certPath,
  303. "--key-file", privateKeyPath,
  304. "--ca-file", caPath,
  305. }
  306. args = append(args, tlsClientArgs...)
  307. }
  308. if cfg.isPeerTLS {
  309. if cfg.isPeerAutoTLS {
  310. args = append(args, "--peer-auto-tls=true")
  311. } else {
  312. tlsPeerArgs := []string{
  313. "--peer-cert-file", certPath,
  314. "--peer-key-file", privateKeyPath,
  315. "--peer-ca-file", caPath,
  316. }
  317. args = append(args, tlsPeerArgs...)
  318. }
  319. }
  320. return args
  321. }
  322. func (epc *etcdProcessCluster) Close() (err error) {
  323. for _, p := range epc.procs {
  324. if p == nil {
  325. continue
  326. }
  327. os.RemoveAll(p.cfg.dataDirPath)
  328. if curErr := p.proc.Close(); curErr != nil {
  329. if err != nil {
  330. err = fmt.Errorf("%v; %v", err, curErr)
  331. } else {
  332. err = curErr
  333. }
  334. }
  335. <-p.donec
  336. }
  337. return err
  338. }
  339. func spawnCmd(args []string) (*gexpect.ExpectSubprocess, error) {
  340. // redirect stderr to stdout since gexpect only uses stdout
  341. cmd := `/bin/sh -c "` + strings.Join(args, " ") + ` 2>&1 "`
  342. return gexpect.Spawn(cmd)
  343. }
  344. func spawnWithExpect(args []string, expected string) error {
  345. proc, err := spawnCmd(args)
  346. if err != nil {
  347. return err
  348. }
  349. ok, err := proc.ExpectRegex(expected)
  350. perr := proc.Close()
  351. if err != nil {
  352. return err
  353. }
  354. if !ok {
  355. return fmt.Errorf("couldn't get expected output: '%s'", expected)
  356. }
  357. return perr
  358. }
  359. // spawnWithExpectedString compares outputs in string format.
  360. // This is useful when gexpect does not match regex correctly with
  361. // some UTF-8 format characters.
  362. func spawnWithExpectedString(args []string, expected string) error {
  363. proc, err := spawnCmd(args)
  364. if err != nil {
  365. return err
  366. }
  367. s, err := proc.ReadLine()
  368. perr := proc.Close()
  369. if err != nil {
  370. return err
  371. }
  372. if !strings.Contains(s, expected) {
  373. return fmt.Errorf("expected %q, got %q", expected, s)
  374. }
  375. return perr
  376. }
  377. // proxies returns only the proxy etcdProcess.
  378. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  379. return epc.procs[epc.cfg.clusterSize:]
  380. }
  381. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  382. return epc.procs[:epc.cfg.clusterSize]
  383. }