etcd_test.go 12 KB

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