etcd_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. isPeerTLS bool
  136. isPeerAutoTLS bool
  137. isClientAutoTLS bool
  138. forceNewCluster bool
  139. initialToken string
  140. quotaBackendBytes int64
  141. }
  142. // newEtcdProcessCluster launches a new cluster from etcd processes, returning
  143. // a new etcdProcessCluster once all nodes are ready to accept client requests.
  144. func newEtcdProcessCluster(cfg *etcdProcessClusterConfig) (*etcdProcessCluster, error) {
  145. etcdCfgs := cfg.etcdProcessConfigs()
  146. epc := &etcdProcessCluster{
  147. cfg: cfg,
  148. procs: make([]*etcdProcess, cfg.clusterSize+cfg.proxySize),
  149. }
  150. // launch etcd processes
  151. for i := range etcdCfgs {
  152. proc, err := newEtcdProcess(etcdCfgs[i])
  153. if err != nil {
  154. epc.Close()
  155. return nil, err
  156. }
  157. epc.procs[i] = proc
  158. }
  159. return epc, epc.Start()
  160. }
  161. func newEtcdProcess(cfg *etcdProcessConfig) (*etcdProcess, error) {
  162. if !fileutil.Exist(cfg.execPath) {
  163. return nil, fmt.Errorf("could not find etcd binary")
  164. }
  165. if !cfg.keepDataDir {
  166. if err := os.RemoveAll(cfg.dataDirPath); err != nil {
  167. return nil, err
  168. }
  169. }
  170. child, err := spawnCmd(append([]string{cfg.execPath}, cfg.args...))
  171. if err != nil {
  172. return nil, err
  173. }
  174. return &etcdProcess{cfg: cfg, proc: child, donec: make(chan struct{})}, nil
  175. }
  176. func (cfg *etcdProcessClusterConfig) etcdProcessConfigs() []*etcdProcessConfig {
  177. if cfg.basePort == 0 {
  178. cfg.basePort = etcdProcessBasePort
  179. }
  180. if cfg.execPath == "" {
  181. cfg.execPath = "../bin/etcd"
  182. }
  183. if cfg.snapCount == 0 {
  184. cfg.snapCount = etcdserver.DefaultSnapCount
  185. }
  186. clientScheme := "http"
  187. if cfg.clientTLS == clientTLS {
  188. clientScheme = "https"
  189. }
  190. peerScheme := "http"
  191. if cfg.isPeerTLS {
  192. peerScheme = "https"
  193. }
  194. etcdCfgs := make([]*etcdProcessConfig, cfg.clusterSize+cfg.proxySize)
  195. initialCluster := make([]string, cfg.clusterSize)
  196. for i := 0; i < cfg.clusterSize; i++ {
  197. var curls []string
  198. var curl, curltls string
  199. port := cfg.basePort + 2*i
  200. curlHost := fmt.Sprintf("localhost:%d", port)
  201. switch cfg.clientTLS {
  202. case clientNonTLS, clientTLS:
  203. curl = (&url.URL{Scheme: clientScheme, Host: curlHost}).String()
  204. curls = []string{curl}
  205. case clientTLSAndNonTLS:
  206. curl = (&url.URL{Scheme: "http", Host: curlHost}).String()
  207. curltls = (&url.URL{Scheme: "https", Host: curlHost}).String()
  208. curls = []string{curl, curltls}
  209. }
  210. purl := url.URL{Scheme: peerScheme, Host: fmt.Sprintf("localhost:%d", port+1)}
  211. name := fmt.Sprintf("testname%d", i)
  212. dataDirPath := cfg.dataDirPath
  213. if cfg.dataDirPath == "" {
  214. var derr error
  215. dataDirPath, derr = ioutil.TempDir("", name+".etcd")
  216. if derr != nil {
  217. panic("could not get tempdir for datadir")
  218. }
  219. }
  220. initialCluster[i] = fmt.Sprintf("%s=%s", name, purl.String())
  221. args := []string{
  222. "--name", name,
  223. "--listen-client-urls", strings.Join(curls, ","),
  224. "--advertise-client-urls", strings.Join(curls, ","),
  225. "--listen-peer-urls", purl.String(),
  226. "--initial-advertise-peer-urls", purl.String(),
  227. "--initial-cluster-token", cfg.initialToken,
  228. "--data-dir", dataDirPath,
  229. "--snapshot-count", fmt.Sprintf("%d", cfg.snapCount),
  230. }
  231. if cfg.forceNewCluster {
  232. args = append(args, "--force-new-cluster")
  233. }
  234. if cfg.quotaBackendBytes > 0 {
  235. args = append(args,
  236. "--quota-backend-bytes", fmt.Sprintf("%d", cfg.quotaBackendBytes),
  237. )
  238. }
  239. args = append(args, cfg.tlsArgs()...)
  240. etcdCfgs[i] = &etcdProcessConfig{
  241. execPath: cfg.execPath,
  242. args: args,
  243. dataDirPath: dataDirPath,
  244. keepDataDir: cfg.keepDataDir,
  245. acurl: curl,
  246. acurltls: curltls,
  247. acurlHost: curlHost,
  248. }
  249. }
  250. for i := 0; i < cfg.proxySize; i++ {
  251. port := cfg.basePort + 2*cfg.clusterSize + i + 1
  252. curlHost := fmt.Sprintf("localhost:%d", port)
  253. curl := url.URL{Scheme: clientScheme, Host: curlHost}
  254. name := fmt.Sprintf("testname-proxy%d", i)
  255. dataDirPath, derr := ioutil.TempDir("", name+".etcd")
  256. if derr != nil {
  257. panic("could not get tempdir for datadir")
  258. }
  259. args := []string{
  260. "--name", name,
  261. "--proxy", "on",
  262. "--listen-client-urls", curl.String(),
  263. "--data-dir", dataDirPath,
  264. }
  265. args = append(args, cfg.tlsArgs()...)
  266. etcdCfgs[cfg.clusterSize+i] = &etcdProcessConfig{
  267. execPath: cfg.execPath,
  268. args: args,
  269. dataDirPath: dataDirPath,
  270. keepDataDir: cfg.keepDataDir,
  271. acurl: curl.String(),
  272. acurlHost: curlHost,
  273. isProxy: true,
  274. }
  275. }
  276. initialClusterArgs := []string{"--initial-cluster", strings.Join(initialCluster, ",")}
  277. for i := range etcdCfgs {
  278. etcdCfgs[i].args = append(etcdCfgs[i].args, initialClusterArgs...)
  279. }
  280. return etcdCfgs
  281. }
  282. func (cfg *etcdProcessClusterConfig) tlsArgs() (args []string) {
  283. if cfg.clientTLS != clientNonTLS {
  284. if cfg.isClientAutoTLS {
  285. args = append(args, "--auto-tls=true")
  286. } else {
  287. tlsClientArgs := []string{
  288. "--cert-file", certPath,
  289. "--key-file", privateKeyPath,
  290. "--ca-file", caPath,
  291. }
  292. args = append(args, tlsClientArgs...)
  293. }
  294. }
  295. if cfg.isPeerTLS {
  296. if cfg.isPeerAutoTLS {
  297. args = append(args, "--peer-auto-tls=true")
  298. } else {
  299. tlsPeerArgs := []string{
  300. "--peer-cert-file", certPath,
  301. "--peer-key-file", privateKeyPath,
  302. "--peer-ca-file", caPath,
  303. }
  304. args = append(args, tlsPeerArgs...)
  305. }
  306. }
  307. return args
  308. }
  309. func (epc *etcdProcessCluster) Start() (err error) {
  310. readyC := make(chan error, epc.cfg.clusterSize+epc.cfg.proxySize)
  311. readyStr := "enabled capabilities for version"
  312. for i := range epc.procs {
  313. go func(etcdp *etcdProcess) {
  314. etcdp.donec = make(chan struct{})
  315. rs := readyStr
  316. if etcdp.cfg.isProxy {
  317. rs = "httpproxy: endpoints found"
  318. }
  319. _, err := etcdp.proc.Expect(rs)
  320. readyC <- err
  321. close(etcdp.donec)
  322. }(epc.procs[i])
  323. }
  324. for range epc.procs {
  325. if err := <-readyC; err != nil {
  326. epc.Close()
  327. return err
  328. }
  329. }
  330. return nil
  331. }
  332. func (epc *etcdProcessCluster) RestartAll() error {
  333. for i := range epc.procs {
  334. proc, err := newEtcdProcess(epc.procs[i].cfg)
  335. if err != nil {
  336. epc.Close()
  337. return err
  338. }
  339. epc.procs[i] = proc
  340. }
  341. return epc.Start()
  342. }
  343. func (epr *etcdProcess) Restart() error {
  344. proc, err := newEtcdProcess(epr.cfg)
  345. if err != nil {
  346. epr.Stop()
  347. return err
  348. }
  349. *epr = *proc
  350. readyStr := "enabled capabilities for version"
  351. if proc.cfg.isProxy {
  352. readyStr = "httpproxy: endpoints found"
  353. }
  354. if _, err = proc.proc.Expect(readyStr); err != nil {
  355. epr.Stop()
  356. return err
  357. }
  358. close(proc.donec)
  359. return nil
  360. }
  361. func (epc *etcdProcessCluster) StopAll() (err error) {
  362. for _, p := range epc.procs {
  363. if p == nil {
  364. continue
  365. }
  366. if curErr := p.proc.Stop(); curErr != nil {
  367. if err != nil {
  368. err = fmt.Errorf("%v; %v", err, curErr)
  369. } else {
  370. err = curErr
  371. }
  372. }
  373. <-p.donec
  374. }
  375. return err
  376. }
  377. func (epr *etcdProcess) Stop() error {
  378. if epr == nil {
  379. return nil
  380. }
  381. if err := epr.proc.Stop(); err != nil {
  382. return err
  383. }
  384. <-epr.donec
  385. return nil
  386. }
  387. func (epc *etcdProcessCluster) Close() error {
  388. err := epc.StopAll()
  389. for _, p := range epc.procs {
  390. os.RemoveAll(p.cfg.dataDirPath)
  391. }
  392. return err
  393. }
  394. func spawnCmd(args []string) (*expect.ExpectProcess, error) {
  395. return expect.NewExpect(args[0], args[1:]...)
  396. }
  397. func spawnWithExpect(args []string, expected string) error {
  398. return spawnWithExpects(args, []string{expected}...)
  399. }
  400. func spawnWithExpects(args []string, xs ...string) error {
  401. proc, err := spawnCmd(args)
  402. if err != nil {
  403. return err
  404. }
  405. // process until either stdout or stderr contains
  406. // the expected string
  407. var (
  408. lines []string
  409. lineFunc = func(txt string) bool { return true }
  410. )
  411. for _, txt := range xs {
  412. for {
  413. l, err := proc.ExpectFunc(lineFunc)
  414. if err != nil {
  415. return fmt.Errorf("%v (expected %q, got %q)", err, txt, lines)
  416. }
  417. lines = append(lines, l)
  418. if strings.Contains(l, txt) {
  419. break
  420. }
  421. }
  422. }
  423. perr := proc.Close()
  424. if err != nil {
  425. return err
  426. }
  427. if len(xs) == 0 && proc.LineCount() != 0 { // expect no output
  428. return fmt.Errorf("unexpected output (got lines %q, line count %d)", lines, proc.LineCount())
  429. }
  430. return perr
  431. }
  432. // proxies returns only the proxy etcdProcess.
  433. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  434. return epc.procs[epc.cfg.clusterSize:]
  435. }
  436. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  437. return epc.procs[:epc.cfg.clusterSize]
  438. }
  439. func (epc *etcdProcessCluster) endpoints() []string {
  440. eps := make([]string, epc.cfg.clusterSize)
  441. for i, ep := range epc.backends() {
  442. eps[i] = ep.cfg.acurl
  443. }
  444. return eps
  445. }
  446. func (epc *etcdProcessCluster) grpcEndpoints() []string {
  447. eps := make([]string, epc.cfg.clusterSize)
  448. for i, ep := range epc.backends() {
  449. eps[i] = ep.cfg.acurlHost
  450. }
  451. return eps
  452. }