etcd_test.go 12 KB

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