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. for i := range epc.procs {
  312. go func(n int) { readyC <- epc.procs[n].waitReady() }(i)
  313. }
  314. for range epc.procs {
  315. if err := <-readyC; err != nil {
  316. epc.Close()
  317. return err
  318. }
  319. }
  320. return nil
  321. }
  322. func (epc *etcdProcessCluster) RestartAll() error {
  323. for i := range epc.procs {
  324. proc, err := newEtcdProcess(epc.procs[i].cfg)
  325. if err != nil {
  326. epc.Close()
  327. return err
  328. }
  329. epc.procs[i] = proc
  330. }
  331. return epc.Start()
  332. }
  333. func (epc *etcdProcessCluster) StopAll() (err error) {
  334. for _, p := range epc.procs {
  335. if p == nil {
  336. continue
  337. }
  338. if curErr := p.proc.Stop(); curErr != nil {
  339. if err != nil {
  340. err = fmt.Errorf("%v; %v", err, curErr)
  341. } else {
  342. err = curErr
  343. }
  344. }
  345. <-p.donec
  346. }
  347. return err
  348. }
  349. func (epc *etcdProcessCluster) Close() error {
  350. err := epc.StopAll()
  351. for _, p := range epc.procs {
  352. os.RemoveAll(p.cfg.dataDirPath)
  353. }
  354. return err
  355. }
  356. func (ep *etcdProcess) Restart() error {
  357. newEp, err := newEtcdProcess(ep.cfg)
  358. if err != nil {
  359. ep.Stop()
  360. return err
  361. }
  362. *ep = *newEp
  363. if err = ep.waitReady(); err != nil {
  364. ep.Stop()
  365. return err
  366. }
  367. return nil
  368. }
  369. func (ep *etcdProcess) Stop() error {
  370. if ep == nil {
  371. return nil
  372. }
  373. if err := ep.proc.Stop(); err != nil {
  374. return err
  375. }
  376. <-ep.donec
  377. return nil
  378. }
  379. func (ep *etcdProcess) waitReady() error {
  380. readyStrs := []string{"enabled capabilities for version", "published"}
  381. if ep.cfg.isProxy {
  382. readyStrs = []string{"httpproxy: endpoints found"}
  383. }
  384. c := 0
  385. matchSet := func(l string) bool {
  386. for _, s := range readyStrs {
  387. if strings.Contains(l, s) {
  388. c++
  389. break
  390. }
  391. }
  392. return c == len(readyStrs)
  393. }
  394. _, err := ep.proc.ExpectFunc(matchSet)
  395. close(ep.donec)
  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. }