etcd_test.go 12 KB

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