cluster.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. "math/rand"
  18. "net"
  19. "strings"
  20. "time"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  23. clientv2 "github.com/coreos/etcd/client"
  24. "github.com/coreos/etcd/clientv3"
  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. grpcURLs[i] = fmt.Sprintf("%s:2378", host)
  79. clientURLs[i] = fmt.Sprintf("http://%s:2379", host)
  80. peerURLs[i] = fmt.Sprintf("http://%s:%d", host, peerURLPort)
  81. members[i] = fmt.Sprintf("%s=%s", names[i], peerURLs[i])
  82. }
  83. clusterStr := strings.Join(members, ",")
  84. token := fmt.Sprint(rand.Int())
  85. for i, a := range agents {
  86. flags := []string{
  87. "--name", names[i],
  88. "--data-dir", c.datadir,
  89. "--listen-client-urls", clientURLs[i],
  90. "--advertise-client-urls", clientURLs[i],
  91. "--listen-peer-urls", peerURLs[i],
  92. "--initial-advertise-peer-urls", peerURLs[i],
  93. "--initial-cluster-token", token,
  94. "--initial-cluster", clusterStr,
  95. "--initial-cluster-state", "new",
  96. }
  97. if !c.v2Only {
  98. flags = append(flags,
  99. "--experimental-v3demo",
  100. "--experimental-gRPC-addr", grpcURLs[i],
  101. )
  102. }
  103. if _, err := a.Start(flags...); err != nil {
  104. // cleanup
  105. for j := 0; j < i; j++ {
  106. agents[j].Terminate()
  107. }
  108. return err
  109. }
  110. }
  111. // TODO: Too intensive stressers can panic etcd member with
  112. // 'out of memory' error. Put rate limits in server side.
  113. stressN := 100
  114. var stressers []Stresser
  115. if c.v2Only {
  116. for _, u := range clientURLs {
  117. s := &stresserV2{
  118. Endpoint: u,
  119. KeySize: c.stressKeySize,
  120. KeySuffixRange: c.stressKeySuffixRange,
  121. N: stressN,
  122. }
  123. go s.Stress()
  124. stressers = append(stressers, s)
  125. }
  126. } else {
  127. for _, u := range grpcURLs {
  128. s := &stresser{
  129. Endpoint: u,
  130. KeySize: c.stressKeySize,
  131. KeySuffixRange: c.stressKeySuffixRange,
  132. N: stressN,
  133. }
  134. go s.Stress()
  135. stressers = append(stressers, s)
  136. }
  137. }
  138. c.Size = size
  139. c.Agents = agents
  140. c.Stressers = stressers
  141. c.Names = names
  142. c.GRPCURLs = grpcURLs
  143. c.ClientURLs = clientURLs
  144. return nil
  145. }
  146. func (c *cluster) WaitHealth() error {
  147. var err error
  148. // wait 60s to check cluster health.
  149. // TODO: set it to a reasonable value. It is set that high because
  150. // follower may use long time to catch up the leader when reboot under
  151. // reasonable workload (https://github.com/coreos/etcd/issues/2698)
  152. healthFunc, urls := setHealthKey, c.GRPCURLs
  153. if c.v2Only {
  154. healthFunc, urls = setHealthKeyV2, c.ClientURLs
  155. }
  156. for i := 0; i < 60; i++ {
  157. err = healthFunc(urls)
  158. if err == nil {
  159. return nil
  160. }
  161. time.Sleep(time.Second)
  162. }
  163. return err
  164. }
  165. // GetLeader returns the index of leader and error if any.
  166. func (c *cluster) GetLeader() (int, error) {
  167. if c.v2Only {
  168. return 0, nil
  169. }
  170. cli, err := clientv3.New(clientv3.Config{
  171. Endpoints: c.GRPCURLs,
  172. DialTimeout: 5 * time.Second,
  173. })
  174. if err != nil {
  175. return 0, err
  176. }
  177. defer cli.Close()
  178. clus := clientv3.NewCluster(cli)
  179. mem, err := clus.MemberLeader(context.Background())
  180. if err != nil {
  181. return 0, err
  182. }
  183. for i, name := range c.Names {
  184. if name == mem.Name {
  185. return i, nil
  186. }
  187. }
  188. return 0, fmt.Errorf("no leader found")
  189. }
  190. func (c *cluster) Report() (success, failure int) {
  191. for _, stress := range c.Stressers {
  192. s, f := stress.Report()
  193. success += s
  194. failure += f
  195. }
  196. return
  197. }
  198. func (c *cluster) Cleanup() error {
  199. var lasterr error
  200. for _, a := range c.Agents {
  201. if err := a.Cleanup(); err != nil {
  202. lasterr = err
  203. }
  204. }
  205. for _, s := range c.Stressers {
  206. s.Cancel()
  207. }
  208. return lasterr
  209. }
  210. func (c *cluster) Terminate() {
  211. for _, a := range c.Agents {
  212. a.Terminate()
  213. }
  214. for _, s := range c.Stressers {
  215. s.Cancel()
  216. }
  217. }
  218. func (c *cluster) Status() ClusterStatus {
  219. cs := ClusterStatus{
  220. AgentStatuses: make(map[string]client.Status),
  221. }
  222. for i, a := range c.Agents {
  223. s, err := a.Status()
  224. // TODO: add a.Desc() as a key of the map
  225. desc := c.agentEndpoints[i]
  226. if err != nil {
  227. cs.AgentStatuses[desc] = client.Status{State: "unknown"}
  228. plog.Printf("failed to get the status of agent [%s]", desc)
  229. }
  230. cs.AgentStatuses[desc] = s
  231. }
  232. return cs
  233. }
  234. // setHealthKey sets health key on all given urls.
  235. func setHealthKey(us []string) error {
  236. for _, u := range us {
  237. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  238. if err != nil {
  239. return fmt.Errorf("%v (%s)", err, u)
  240. }
  241. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  242. kvc := pb.NewKVClient(conn)
  243. _, err = kvc.Put(ctx, &pb.PutRequest{Key: []byte("health"), Value: []byte("good")})
  244. cancel()
  245. conn.Close()
  246. if err != nil {
  247. return err
  248. }
  249. }
  250. return nil
  251. }
  252. // setHealthKeyV2 sets health key on all given urls.
  253. func setHealthKeyV2(us []string) error {
  254. for _, u := range us {
  255. cfg := clientv2.Config{
  256. Endpoints: []string{u},
  257. }
  258. c, err := clientv2.New(cfg)
  259. if err != nil {
  260. return err
  261. }
  262. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  263. kapi := clientv2.NewKeysAPI(c)
  264. _, err = kapi.Set(ctx, "health", "good", nil)
  265. cancel()
  266. if err != nil {
  267. return err
  268. }
  269. }
  270. return nil
  271. }
  272. func (c *cluster) getRevisionHash() (map[string]int64, map[string]int64, error) {
  273. revs := make(map[string]int64)
  274. hashes := make(map[string]int64)
  275. for _, u := range c.GRPCURLs {
  276. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  277. if err != nil {
  278. return nil, nil, err
  279. }
  280. kvc := pb.NewKVClient(conn)
  281. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  282. resp, err := kvc.Hash(ctx, &pb.HashRequest{})
  283. cancel()
  284. conn.Close()
  285. if err != nil {
  286. return nil, nil, err
  287. }
  288. revs[u] = resp.Header.Revision
  289. hashes[u] = int64(resp.Hash)
  290. }
  291. return revs, hashes, nil
  292. }
  293. func (c *cluster) compactKV(rev int64) error {
  294. var (
  295. conn *grpc.ClientConn
  296. err error
  297. )
  298. for _, u := range c.GRPCURLs {
  299. conn, err = grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  300. if err != nil {
  301. continue
  302. }
  303. kvc := pb.NewKVClient(conn)
  304. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  305. _, err = kvc.Compact(ctx, &pb.CompactionRequest{Revision: rev})
  306. cancel()
  307. conn.Close()
  308. if err == nil {
  309. return nil
  310. }
  311. }
  312. return err
  313. }