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. for i := range epc.procs {
  316. go func(n int) { readyC <- epc.procs[n].waitReady() }(i)
  317. }
  318. for range epc.procs {
  319. if err := <-readyC; err != nil {
  320. epc.Close()
  321. return err
  322. }
  323. }
  324. return nil
  325. }
  326. func (epc *etcdProcessCluster) RestartAll() error {
  327. for i := range epc.procs {
  328. proc, err := newEtcdProcess(epc.procs[i].cfg)
  329. if err != nil {
  330. epc.Close()
  331. return err
  332. }
  333. epc.procs[i] = proc
  334. }
  335. return epc.Start()
  336. }
  337. func (epc *etcdProcessCluster) StopAll() (err error) {
  338. for _, p := range epc.procs {
  339. if p == nil {
  340. continue
  341. }
  342. if curErr := p.proc.Stop(); curErr != nil {
  343. if err != nil {
  344. err = fmt.Errorf("%v; %v", err, curErr)
  345. } else {
  346. err = curErr
  347. }
  348. }
  349. <-p.donec
  350. }
  351. return err
  352. }
  353. func (epc *etcdProcessCluster) Close() error {
  354. err := epc.StopAll()
  355. for _, p := range epc.procs {
  356. os.RemoveAll(p.cfg.dataDirPath)
  357. }
  358. return err
  359. }
  360. func (ep *etcdProcess) Restart() error {
  361. newEp, err := newEtcdProcess(ep.cfg)
  362. if err != nil {
  363. ep.Stop()
  364. return err
  365. }
  366. *ep = *newEp
  367. if err = ep.waitReady(); err != nil {
  368. ep.Stop()
  369. return err
  370. }
  371. return nil
  372. }
  373. func (ep *etcdProcess) Stop() error {
  374. if ep == nil {
  375. return nil
  376. }
  377. if err := ep.proc.Stop(); err != nil {
  378. return err
  379. }
  380. <-ep.donec
  381. return nil
  382. }
  383. func (ep *etcdProcess) waitReady() error {
  384. readyStrs := []string{"enabled capabilities for version", "published"}
  385. if ep.cfg.isProxy {
  386. readyStrs = []string{"httpproxy: endpoints found"}
  387. }
  388. c := 0
  389. matchSet := func(l string) bool {
  390. for _, s := range readyStrs {
  391. if strings.Contains(l, s) {
  392. c++
  393. break
  394. }
  395. }
  396. return c == len(readyStrs)
  397. }
  398. _, err := ep.proc.ExpectFunc(matchSet)
  399. close(ep.donec)
  400. return err
  401. }
  402. func spawnCmd(args []string) (*expect.ExpectProcess, error) {
  403. return expect.NewExpect(args[0], args[1:]...)
  404. }
  405. func spawnWithExpect(args []string, expected string) error {
  406. return spawnWithExpects(args, []string{expected}...)
  407. }
  408. func spawnWithExpects(args []string, xs ...string) error {
  409. proc, err := spawnCmd(args)
  410. if err != nil {
  411. return err
  412. }
  413. // process until either stdout or stderr contains
  414. // the expected string
  415. var (
  416. lines []string
  417. lineFunc = func(txt string) bool { return true }
  418. )
  419. for _, txt := range xs {
  420. for {
  421. l, err := proc.ExpectFunc(lineFunc)
  422. if err != nil {
  423. return fmt.Errorf("%v (expected %q, got %q)", err, txt, lines)
  424. }
  425. lines = append(lines, l)
  426. if strings.Contains(l, txt) {
  427. break
  428. }
  429. }
  430. }
  431. perr := proc.Close()
  432. if err != nil {
  433. return err
  434. }
  435. if len(xs) == 0 && proc.LineCount() != 0 { // expect no output
  436. return fmt.Errorf("unexpected output (got lines %q, line count %d)", lines, proc.LineCount())
  437. }
  438. return perr
  439. }
  440. // proxies returns only the proxy etcdProcess.
  441. func (epc *etcdProcessCluster) proxies() []*etcdProcess {
  442. return epc.procs[epc.cfg.clusterSize:]
  443. }
  444. func (epc *etcdProcessCluster) backends() []*etcdProcess {
  445. return epc.procs[:epc.cfg.clusterSize]
  446. }
  447. func (epc *etcdProcessCluster) endpoints() []string {
  448. eps := make([]string, epc.cfg.clusterSize)
  449. for i, ep := range epc.backends() {
  450. eps[i] = ep.cfg.acurl
  451. }
  452. return eps
  453. }
  454. func (epc *etcdProcessCluster) grpcEndpoints() []string {
  455. eps := make([]string, epc.cfg.clusterSize)
  456. for i, ep := range epc.backends() {
  457. eps[i] = ep.cfg.acurlHost
  458. }
  459. return eps
  460. }