etcd_test.go 12 KB

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