etcd_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. // Copyright 2016 The etcd Authors
  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. "net/url"
  19. "os"
  20. "strings"
  21. "github.com/coreos/etcd/etcdserver"
  22. "github.com/coreos/etcd/pkg/expect"
  23. "github.com/coreos/etcd/pkg/fileutil"
  24. )
  25. const (
  26. etcdProcessBasePort = 20000
  27. certPath = "../integration/fixtures/server.crt"
  28. privateKeyPath = "../integration/fixtures/server.key.insecure"
  29. caPath = "../integration/fixtures/ca.crt"
  30. )
  31. type clientConnType int
  32. const (
  33. clientNonTLS clientConnType = iota
  34. clientTLS
  35. clientTLSAndNonTLS
  36. )
  37. var (
  38. configNoTLS = etcdProcessClusterConfig{
  39. clusterSize: 3,
  40. proxySize: 0,
  41. initialToken: "new",
  42. }
  43. configAutoTLS = etcdProcessClusterConfig{
  44. clusterSize: 3,
  45. isPeerTLS: true,
  46. isPeerAutoTLS: true,
  47. initialToken: "new",
  48. }
  49. configTLS = etcdProcessClusterConfig{
  50. clusterSize: 3,
  51. proxySize: 0,
  52. clientTLS: clientTLS,
  53. isPeerTLS: true,
  54. initialToken: "new",
  55. }
  56. configClientTLS = etcdProcessClusterConfig{
  57. clusterSize: 3,
  58. proxySize: 0,
  59. clientTLS: clientTLS,
  60. initialToken: "new",
  61. }
  62. configClientBoth = etcdProcessClusterConfig{
  63. clusterSize: 1,
  64. proxySize: 0,
  65. clientTLS: clientTLSAndNonTLS,
  66. initialToken: "new",
  67. }
  68. configClientAutoTLS = etcdProcessClusterConfig{
  69. clusterSize: 1,
  70. proxySize: 0,
  71. isClientAutoTLS: true,
  72. clientTLS: clientTLS,
  73. initialToken: "new",
  74. }
  75. configPeerTLS = etcdProcessClusterConfig{
  76. clusterSize: 3,
  77. proxySize: 0,
  78. isPeerTLS: true,
  79. initialToken: "new",
  80. }
  81. configWithProxy = etcdProcessClusterConfig{
  82. clusterSize: 3,
  83. proxySize: 1,
  84. initialToken: "new",
  85. }
  86. configWithProxyTLS = etcdProcessClusterConfig{
  87. clusterSize: 3,
  88. proxySize: 1,
  89. clientTLS: clientTLS,
  90. isPeerTLS: true,
  91. initialToken: "new",
  92. }
  93. configWithProxyPeerTLS = etcdProcessClusterConfig{
  94. clusterSize: 3,
  95. proxySize: 1,
  96. isPeerTLS: true,
  97. initialToken: "new",
  98. }
  99. )
  100. func configStandalone(cfg etcdProcessClusterConfig) *etcdProcessClusterConfig {
  101. ret := cfg
  102. ret.clusterSize = 1
  103. return &ret
  104. }
  105. type etcdProcessCluster struct {
  106. cfg *etcdProcessClusterConfig
  107. procs []*etcdProcess
  108. }
  109. type etcdProcess struct {
  110. cfg *etcdProcessConfig
  111. proc *expect.ExpectProcess
  112. donec chan struct{} // closed when Interact() terminates
  113. }
  114. type etcdProcessConfig struct {
  115. execPath string
  116. args []string
  117. dataDirPath string
  118. keepDataDir bool
  119. acurl string
  120. // additional url for tls connection when the etcd process
  121. // serves both http and https
  122. acurltls string
  123. acurlHost string
  124. isProxy bool
  125. }
  126. type etcdProcessClusterConfig struct {
  127. execPath string
  128. dataDirPath string
  129. keepDataDir bool
  130. clusterSize int
  131. basePort int
  132. proxySize int
  133. snapCount int // default is 10000
  134. clientTLS clientConnType
  135. clientCertAuthEnabled bool
  136. isPeerTLS bool
  137. isPeerAutoTLS bool
  138. isClientAutoTLS bool
  139. forceNewCluster bool
  140. initialToken string
  141. quotaBackendBytes int64
  142. }
  143. // newEtcdProcessCluster launches a new cluster from etcd processes, returning
  144. // a new etcdProcessCluster once all nodes are ready to accept client requests.
  145. func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
  146. etcdCfgs := cfg.etcdProcessConfigs()
  147. epc := &etcdProcessCluster{
  148. cfg: cfg,
  149. procs: make([]*etcdProcess, cfg.clusterSize+cfg.proxySize),
  150. }
  151. // launch etcd processes
  152. for i := range etcdCfgs {
  153. proc, err := newEtcdProcess(etcdCfgs[i])
  154. if err != nil {
  155. epc.Close()
  156. return nil, err
  157. }
  158. epc.procs[i] = proc
  159. }
  160. return epc, epc.Start()
  161. }
  162. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  163. if !fileutil.Exist(cfg.execPath) {
  164. return nil, fmt.Errorf("could not find etcd binary")
  165. }
  166. if !cfg.keepDataDir {
  167. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  168. return nil, err
  169. }
  170. }
  171. child, err := spawnCmd(append([]string{cfg.execPath}, cfg.args...))
  172. if err != nil {
  173. return nil, err
  174. }
  175. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  176. }
  177. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  178. if cfg.basePort == 0 {
  179. cfg.basePort = etcdProcessBasePort
  180. }
  181. if cfg.execPath == "" {
  182. cfg.execPath = "../bin/etcd"
  183. }
  184. if cfg.snapCount == 0 {
  185. cfg.snapCount = etcdserver.DefaultSnapCount
  186. }
  187. clientScheme := "http"
  188. if cfg.clientTLS == clientTLS {
  189. clientScheme = "https"
  190. }
  191. peerScheme := "http"
  192. if cfg.isPeerTLS {
  193. peerScheme = "https"
  194. }
  195. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize+cfg.proxySize)
  196. initialCluster := make([]string, cfg.clusterSize)
  197. for i := 0; i < cfg.clusterSize; i++ {
  198. var curls []string
  199. var curl, curltls string
  200. port := cfg.basePort + 2*i
  201. curlHost := fmt.Sprintf("localhost:%d", port)
  202. switch cfg.clientTLS {
  203. case clientNonTLS, clientTLS:
  204. curl = (&url.URL{Scheme: clientScheme, Host: curlHost}).String()
  205. curls = []string{curl}
  206. case clientTLSAndNonTLS:
  207. curl = (&url.URL{Scheme: "http", Host: curlHost}).String()
  208. curltls = (&url.URL{Scheme: "https", Host: curlHost}).String()
  209. curls = []string{curl, curltls}
  210. }
  211. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  212. name := fmt.Sprintf("testname%d", i)
  213. dataDirPath := cfg.dataDirPath
  214. if cfg.dataDirPath == "" {
  215. var derr error
  216. dataDirPath, derr = ioutil.TempDir("", name+".etcd")
  217. if derr != nil {
  218. panic("could not get tempdir for datadir")
  219. }
  220. }
  221. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  222. args := []string{
  223. "--name", name,
  224. "--listen-client-urls", strings.Join(curls, ","),
  225. "--advertise-client-urls", strings.Join(curls, ","),
  226. "--listen-peer-urls", purl.String(),
  227. "--initial-advertise-peer-urls", purl.String(),
  228. "--initial-cluster-token", cfg.initialToken,
  229. "--data-dir", dataDirPath,
  230. "--snapshot-count", fmt.Sprintf("%d", cfg.snapCount),
  231. }
  232. if cfg.forceNewCluster {
  233. args = append(args, "--force-new-cluster")
  234. }
  235. if cfg.quotaBackendBytes > 0 {
  236. args = append(args,
  237. "--quota-backend-bytes", fmt.Sprintf("%d", cfg.quotaBackendBytes),
  238. )
  239. }
  240. args = append(args, cfg.tlsArgs()...)
  241. etcdCfgs[i] = &etcdProcessConfig{
  242. execPath: cfg.execPath,
  243. args: args,
  244. dataDirPath: dataDirPath,
  245. keepDataDir: cfg.keepDataDir,
  246. acurl: curl,
  247. acurltls: curltls,
  248. acurlHost: curlHost,
  249. }
  250. }
  251. for i := 0; i < cfg.proxySize; i++ {
  252. port := cfg.basePort + 2*cfg.clusterSize + i + 1
  253. curlHost := fmt.Sprintf("localhost:%d", port)
  254. curl := url.URL{Scheme: clientScheme, Host: curlHost}
  255. name := fmt.Sprintf("testname-proxy%d", i)
  256. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  257. if derr != nil {
  258. panic("could not get tempdir for datadir")
  259. }
  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. execPath: cfg.execPath,
  269. args: args,
  270. dataDirPath: dataDirPath,
  271. keepDataDir: cfg.keepDataDir,
  272. acurl: curl.String(),
  273. acurlHost: curlHost,
  274. isProxy: true,
  275. }
  276. }
  277. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  278. for i := range etcdCfgs {
  279. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  280. }
  281. return etcdCfgs
  282. }
  283. func (cfg *etcdProcessClusterConfig) tlsArgs() (args []string) {
  284. if cfg.clientTLS != clientNonTLS {
  285. if cfg.isClientAutoTLS {
  286. args = append(args, "--auto-tls=true")
  287. } else {
  288. tlsClientArgs := []string{
  289. "--cert-file", certPath,
  290. "--key-file", privateKeyPath,
  291. "--ca-file", caPath,
  292. }
  293. args = append(args, tlsClientArgs...)
  294. if cfg.clientCertAuthEnabled {
  295. args = append(args, "--client-cert-auth")
  296. }
  297. }
  298. }
  299. if cfg.isPeerTLS {
  300. if cfg.isPeerAutoTLS {
  301. args = append(args, "--peer-auto-tls=true")
  302. } else {
  303. tlsPeerArgs := []string{
  304. "--peer-cert-file", certPath,
  305. "--peer-key-file", privateKeyPath,
  306. "--peer-ca-file", caPath,
  307. }
  308. args = append(args, tlsPeerArgs...)
  309. }
  310. }
  311. return args
  312. }
  313. func (epc *etcdProcessCluster) Start() (err error) {
  314. readyC := make(chan error, epc.cfg.clusterSize+epc.cfg.proxySize)
  315. readyStr := "enabled capabilities for version"
  316. for i := range epc.procs {
  317. go func(etcdp *etcdProcess) {
  318. etcdp.donec = make(chan struct{})
  319. rs := readyStr
  320. if etcdp.cfg.isProxy {
  321. rs = "httpproxy: endpoints found"
  322. }
  323. _, err := etcdp.proc.Expect(rs)
  324. readyC <- err
  325. close(etcdp.donec)
  326. }(epc.procs[i])
  327. }
  328. for range epc.procs {
  329. if err := <-readyC; err != nil {
  330. epc.Close()
  331. return err
  332. }
  333. }
  334. return nil
  335. }
  336. func (epc *etcdProcessCluster) RestartAll() error {
  337. for i := range epc.procs {
  338. proc, err := newEtcdProcess(epc.procs[i].cfg)
  339. if err != nil {
  340. epc.Close()
  341. return err
  342. }
  343. epc.procs[i] = proc
  344. }
  345. return epc.Start()
  346. }
  347. func (epr *etcdProcess) Restart() error {
  348. proc, err := newEtcdProcess(epr.cfg)
  349. if err != nil {
  350. epr.Stop()
  351. return err
  352. }
  353. *epr = *proc
  354. readyStr := "enabled capabilities for version"
  355. if proc.cfg.isProxy {
  356. readyStr = "httpproxy: endpoints found"
  357. }
  358. if _, err = proc.proc.Expect(readyStr); err != nil {
  359. epr.Stop()
  360. return err
  361. }
  362. close(proc.donec)
  363. return nil
  364. }
  365. func (epc *etcdProcessCluster) StopAll() (err error) {
  366. for _, p := range epc.procs {
  367. if p == nil {
  368. continue
  369. }
  370. if curErr := p.proc.Stop(); curErr != nil {
  371. if err != nil {
  372. err = fmt.Errorf("%v; %v", err, curErr)
  373. } else {
  374. err = curErr
  375. }
  376. }
  377. <-p.donec
  378. }
  379. return err
  380. }
  381. func (epr *etcdProcess) Stop() error {
  382. if epr == nil {
  383. return nil
  384. }
  385. if err := epr.proc.Stop(); err != nil {
  386. return err
  387. }
  388. <-epr.donec
  389. return nil
  390. }
  391. func (epc *etcdProcessCluster) Close() error {
  392. err := epc.StopAll()
  393. for _, p := range epc.procs {
  394. os.RemoveAll(p.cfg.dataDirPath)
  395. }
  396. return err
  397. }
  398. func spawnCmd(args []string) (*expect.ExpectProcess, error) {
  399. return expect.NewExpect(args[0], args[1:]...)
  400. }
  401. func spawnWithExpect(args []string, expected string) error {
  402. return spawnWithExpects(args, []string{expected}...)
  403. }
  404. func spawnWithExpects(args []string, xs ...string) error {
  405. proc, err := spawnCmd(args)
  406. if err != nil {
  407. return err
  408. }
  409. // process until either stdout or stderr contains
  410. // the expected string
  411. var (
  412. lines []string
  413. lineFunc = func(txt string) bool { return true }
  414. )
  415. for _, txt := range xs {
  416. for {
  417. l, err := proc.ExpectFunc(lineFunc)
  418. if err != nil {
  419. return fmt.Errorf("%v (expected %q, got %q)", err, txt, lines)
  420. }
  421. lines = append(lines, l)
  422. if strings.Contains(l, txt) {
  423. break
  424. }
  425. }
  426. }
  427. perr := proc.Close()
  428. if err != nil {
  429. return err
  430. }
  431. if len(xs) == 0 && proc.LineCount() != 0 { // expect no output
  432. return fmt.Errorf("unexpected output (got lines %q, line count %d)", lines, proc.LineCount())
  433. }
  434. return perr
  435. }
  436. // proxies returns only the proxy etcdProcess.
  437. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  438. return epc.procs[epc.cfg.clusterSize:]
  439. }
  440. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  441. return epc.procs[:epc.cfg.clusterSize]
  442. }
  443. func (epc *etcdProcessCluster) endpoints() []string {
  444. eps := make([]string, epc.cfg.clusterSize)
  445. for i, ep := range epc.backends() {
  446. eps[i] = ep.cfg.acurl
  447. }
  448. return eps
  449. }
  450. func (epc *etcdProcessCluster) grpcEndpoints() []string {
  451. eps := make([]string, epc.cfg.clusterSize)
  452. for i, ep := range epc.backends() {
  453. eps[i] = ep.cfg.acurlHost
  454. }
  455. return eps
  456. }