cluster.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright 2015 CoreOS, Inc.
  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 main
  15. import (
  16. "fmt"
  17. "log"
  18. "math/rand"
  19. "net"
  20. "strings"
  21. "time"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  24. clientV2 "github.com/coreos/etcd/client"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/coreos/etcd/tools/functional-tester/etcd-agent/client"
  27. )
  28. const peerURLPort = 2380
  29. type cluster struct {
  30. v2Only bool // to be deprecated
  31. agentEndpoints []string
  32. datadir string
  33. stressKeySize int
  34. stressKeySuffixRange int
  35. Size int
  36. Agents []client.Agent
  37. Stressers []Stresser
  38. Names []string
  39. GRPCURLs []string
  40. ClientURLs []string
  41. }
  42. type ClusterStatus struct {
  43. AgentStatuses map[string]client.Status
  44. }
  45. // newCluster starts and returns a new cluster. The caller should call Terminate when finished, to shut it down.
  46. func newCluster(agentEndpoints []string, datadir string, stressKeySize, stressKeySuffixRange int, isV2Only bool) (*cluster, error) {
  47. c := &cluster{
  48. v2Only: isV2Only,
  49. agentEndpoints: agentEndpoints,
  50. datadir: datadir,
  51. stressKeySize: stressKeySize,
  52. stressKeySuffixRange: stressKeySuffixRange,
  53. }
  54. if err := c.Bootstrap(); err != nil {
  55. return nil, err
  56. }
  57. return c, nil
  58. }
  59. func (c *cluster) Bootstrap() error {
  60. size := len(c.agentEndpoints)
  61. agents := make([]client.Agent, size)
  62. names := make([]string, size)
  63. grpcURLs := make([]string, size)
  64. clientURLs := make([]string, size)
  65. peerURLs := make([]string, size)
  66. members := make([]string, size)
  67. for i, u := range c.agentEndpoints {
  68. var err error
  69. agents[i], err = client.NewAgent(u)
  70. if err != nil {
  71. return err
  72. }
  73. names[i] = fmt.Sprintf("etcd-%d", i)
  74. host, _, err := net.SplitHostPort(u)
  75. if err != nil {
  76. return err
  77. }
  78. clientURLs[i] = fmt.Sprintf("http://%s:2379", host)
  79. peerURLs[i] = fmt.Sprintf("http://%s:%d", host, peerURLPort)
  80. members[i] = fmt.Sprintf("%s=%s", names[i], peerURLs[i])
  81. }
  82. clusterStr := strings.Join(members, ",")
  83. token := fmt.Sprint(rand.Int())
  84. for i, a := range agents {
  85. flags := []string{
  86. "--name", names[i],
  87. "--data-dir", c.datadir,
  88. "--listen-client-urls", clientURLs[i],
  89. "--advertise-client-urls", clientURLs[i],
  90. "--listen-peer-urls", peerURLs[i],
  91. "--initial-advertise-peer-urls", peerURLs[i],
  92. "--initial-cluster-token", token,
  93. "--initial-cluster", clusterStr,
  94. "--initial-cluster-state", "new",
  95. }
  96. if !c.v2Only {
  97. flags = append(flags,
  98. "--experimental-v3demo",
  99. "--experimental-gRPC-addr", grpcURLs[i],
  100. )
  101. }
  102. if _, err := a.Start(flags...); err != nil {
  103. // cleanup
  104. for j := 0; j < i; j++ {
  105. agents[j].Terminate()
  106. }
  107. return err
  108. }
  109. }
  110. var stressers []Stresser
  111. if c.v2Only {
  112. for _, u := range clientURLs {
  113. s := &stresserV2{
  114. Endpoint: u,
  115. KeySize: c.stressKeySize,
  116. KeySuffixRange: c.stressKeySuffixRange,
  117. N: 200,
  118. }
  119. go s.Stress()
  120. stressers = append(stressers, s)
  121. }
  122. } else {
  123. for _, u := range grpcURLs {
  124. s := &stresser{
  125. Endpoint: u,
  126. KeySize: c.stressKeySize,
  127. KeySuffixRange: c.stressKeySuffixRange,
  128. N: 200,
  129. }
  130. go s.Stress()
  131. stressers = append(stressers, s)
  132. }
  133. }
  134. c.Size = size
  135. c.Agents = agents
  136. c.Stressers = stressers
  137. c.Names = names
  138. c.GRPCURLs = grpcURLs
  139. c.ClientURLs = clientURLs
  140. return nil
  141. }
  142. func (c *cluster) WaitHealth() error {
  143. var err error
  144. // wait 60s to check cluster health.
  145. // TODO: set it to a reasonable value. It is set that high because
  146. // follower may use long time to catch up the leader when reboot under
  147. // reasonable workload (https://github.com/coreos/etcd/issues/2698)
  148. healthFunc, urls := setHealthKey, c.GRPCURLs
  149. if c.v2Only {
  150. healthFunc = setHealthKeyV2
  151. urls = c.ClientURLs
  152. }
  153. for i := 0; i < 60; i++ {
  154. err = healthFunc(urls)
  155. if err == nil {
  156. return nil
  157. }
  158. time.Sleep(time.Second)
  159. }
  160. return err
  161. }
  162. func (c *cluster) Report() (success, failure int) {
  163. for _, stress := range c.Stressers {
  164. s, f := stress.Report()
  165. success += s
  166. failure += f
  167. }
  168. return
  169. }
  170. func (c *cluster) Cleanup() error {
  171. var lasterr error
  172. for _, a := range c.Agents {
  173. if err := a.Cleanup(); err != nil {
  174. lasterr = err
  175. }
  176. }
  177. for _, s := range c.Stressers {
  178. s.Cancel()
  179. }
  180. return lasterr
  181. }
  182. func (c *cluster) Terminate() {
  183. for _, a := range c.Agents {
  184. a.Terminate()
  185. }
  186. for _, s := range c.Stressers {
  187. s.Cancel()
  188. }
  189. }
  190. func (c *cluster) Status() ClusterStatus {
  191. cs := ClusterStatus{
  192. AgentStatuses: make(map[string]client.Status),
  193. }
  194. for i, a := range c.Agents {
  195. s, err := a.Status()
  196. // TODO: add a.Desc() as a key of the map
  197. desc := c.agentEndpoints[i]
  198. if err != nil {
  199. cs.AgentStatuses[desc] = client.Status{State: "unknown"}
  200. log.Printf("etcd-tester: failed to get the status of agent [%s]", desc)
  201. }
  202. cs.AgentStatuses[desc] = s
  203. }
  204. return cs
  205. }
  206. // setHealthKey sets health key on all given urls.
  207. func setHealthKey(us []string) error {
  208. for _, u := range us {
  209. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  210. if err != nil {
  211. return fmt.Errorf("no connection available for %s (%v)", u, err)
  212. }
  213. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  214. kvc := pb.NewKVClient(conn)
  215. _, err = kvc.Put(ctx, &pb.PutRequest{Key: []byte("health"), Value: []byte("good")})
  216. cancel()
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. return nil
  222. }
  223. // setHealthKeyV2 sets health key on all given urls.
  224. func setHealthKeyV2(us []string) error {
  225. for _, u := range us {
  226. cfg := clientV2.Config{
  227. Endpoints: []string{u},
  228. }
  229. c, err := clientV2.New(cfg)
  230. if err != nil {
  231. return err
  232. }
  233. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  234. kapi := clientV2.NewKeysAPI(c)
  235. _, err = kapi.Set(ctx, "health", "good", nil)
  236. cancel()
  237. if err != nil {
  238. return err
  239. }
  240. }
  241. return nil
  242. }