cluster.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. ClientURLs []string
  40. }
  41. type ClusterStatus struct {
  42. AgentStatuses map[string]client.Status
  43. }
  44. // newCluster starts and returns a new cluster. The caller should call Terminate when finished, to shut it down.
  45. func newCluster(agentEndpoints []string, datadir string, stressKeySize, stressKeySuffixRange int, isV2Only bool) (*cluster, error) {
  46. c := &cluster{
  47. v2Only: isV2Only,
  48. agentEndpoints: agentEndpoints,
  49. datadir: datadir,
  50. stressKeySize: stressKeySize,
  51. stressKeySuffixRange: stressKeySuffixRange,
  52. }
  53. if err := c.Bootstrap(); err != nil {
  54. return nil, err
  55. }
  56. return c, nil
  57. }
  58. func (c *cluster) Bootstrap() error {
  59. size := len(c.agentEndpoints)
  60. agents := make([]client.Agent, size)
  61. names := make([]string, size)
  62. grpcURLs := make([]string, size)
  63. clientURLs := make([]string, size)
  64. peerURLs := make([]string, size)
  65. members := make([]string, size)
  66. for i, u := range c.agentEndpoints {
  67. var err error
  68. agents[i], err = client.NewAgent(u)
  69. if err != nil {
  70. return err
  71. }
  72. names[i] = fmt.Sprintf("etcd-%d", i)
  73. host, _, err := net.SplitHostPort(u)
  74. if err != nil {
  75. return err
  76. }
  77. clientURLs[i] = fmt.Sprintf("http://%s:2379", host)
  78. peerURLs[i] = fmt.Sprintf("http://%s:%d", host, peerURLPort)
  79. members[i] = fmt.Sprintf("%s=%s", names[i], peerURLs[i])
  80. }
  81. clusterStr := strings.Join(members, ",")
  82. token := fmt.Sprint(rand.Int())
  83. for i, a := range agents {
  84. flags := []string{
  85. "--name", names[i],
  86. "--data-dir", c.datadir,
  87. "--listen-client-urls", clientURLs[i],
  88. "--advertise-client-urls", clientURLs[i],
  89. "--listen-peer-urls", peerURLs[i],
  90. "--initial-advertise-peer-urls", peerURLs[i],
  91. "--initial-cluster-token", token,
  92. "--initial-cluster", clusterStr,
  93. "--initial-cluster-state", "new",
  94. }
  95. if !c.v2Only {
  96. flags = append(flags,
  97. "--experimental-v3demo")
  98. }
  99. if _, err := a.Start(flags...); err != nil {
  100. // cleanup
  101. for j := 0; j < i; j++ {
  102. agents[j].Terminate()
  103. }
  104. return err
  105. }
  106. }
  107. // TODO: Too intensive stressers can panic etcd member with
  108. // 'out of memory' error. Put rate limits in server side.
  109. stressN := 100
  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: stressN,
  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: stressN,
  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.ClientURLs = clientURLs
  139. return nil
  140. }
  141. func (c *cluster) WaitHealth() error {
  142. var err error
  143. // wait 60s to check cluster health.
  144. // TODO: set it to a reasonable value. It is set that high because
  145. // follower may use long time to catch up the leader when reboot under
  146. // reasonable workload (https://github.com/coreos/etcd/issues/2698)
  147. healthFunc, urls := setHealthKey, c.ClientURLs
  148. if c.v2Only {
  149. healthFunc, urls = setHealthKeyV2, c.ClientURLs
  150. }
  151. for i := 0; i < 60; i++ {
  152. err = healthFunc(urls)
  153. if err == nil {
  154. return nil
  155. }
  156. time.Sleep(time.Second)
  157. }
  158. return err
  159. }
  160. // GetLeader returns the index of leader and error if any.
  161. func (c *cluster) GetLeader() (int, error) {
  162. if c.v2Only {
  163. return 0, nil
  164. }
  165. cli, err := clientv3.New(clientv3.Config{
  166. Endpoints: c.ClientURLs,
  167. DialTimeout: 5 * time.Second,
  168. })
  169. if err != nil {
  170. return 0, err
  171. }
  172. defer cli.Close()
  173. clus := clientv3.NewCluster(cli)
  174. mem, err := clus.MemberLeader(context.Background())
  175. if err != nil {
  176. return 0, err
  177. }
  178. for i, name := range c.Names {
  179. if name == mem.Name {
  180. return i, nil
  181. }
  182. }
  183. return 0, fmt.Errorf("no leader found")
  184. }
  185. func (c *cluster) Report() (success, failure int) {
  186. for _, stress := range c.Stressers {
  187. s, f := stress.Report()
  188. success += s
  189. failure += f
  190. }
  191. return
  192. }
  193. func (c *cluster) Cleanup() error {
  194. var lasterr error
  195. for _, a := range c.Agents {
  196. if err := a.Cleanup(); err != nil {
  197. lasterr = err
  198. }
  199. }
  200. for _, s := range c.Stressers {
  201. s.Cancel()
  202. }
  203. return lasterr
  204. }
  205. func (c *cluster) Terminate() {
  206. for _, a := range c.Agents {
  207. a.Terminate()
  208. }
  209. for _, s := range c.Stressers {
  210. s.Cancel()
  211. }
  212. }
  213. func (c *cluster) Status() ClusterStatus {
  214. cs := ClusterStatus{
  215. AgentStatuses: make(map[string]client.Status),
  216. }
  217. for i, a := range c.Agents {
  218. s, err := a.Status()
  219. // TODO: add a.Desc() as a key of the map
  220. desc := c.agentEndpoints[i]
  221. if err != nil {
  222. cs.AgentStatuses[desc] = client.Status{State: "unknown"}
  223. plog.Printf("failed to get the status of agent [%s]", desc)
  224. }
  225. cs.AgentStatuses[desc] = s
  226. }
  227. return cs
  228. }
  229. // setHealthKey sets health key on all given urls.
  230. func setHealthKey(us []string) error {
  231. for _, u := range us {
  232. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  233. if err != nil {
  234. return fmt.Errorf("%v (%s)", err, u)
  235. }
  236. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  237. kvc := pb.NewKVClient(conn)
  238. _, err = kvc.Put(ctx, &pb.PutRequest{Key: []byte("health"), Value: []byte("good")})
  239. cancel()
  240. conn.Close()
  241. if err != nil {
  242. return err
  243. }
  244. }
  245. return nil
  246. }
  247. // setHealthKeyV2 sets health key on all given urls.
  248. func setHealthKeyV2(us []string) error {
  249. for _, u := range us {
  250. cfg := clientv2.Config{
  251. Endpoints: []string{u},
  252. }
  253. c, err := clientv2.New(cfg)
  254. if err != nil {
  255. return err
  256. }
  257. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  258. kapi := clientv2.NewKeysAPI(c)
  259. _, err = kapi.Set(ctx, "health", "good", nil)
  260. cancel()
  261. if err != nil {
  262. return err
  263. }
  264. }
  265. return nil
  266. }
  267. func (c *cluster) getRevisionHash() (map[string]int64, map[string]int64, error) {
  268. revs := make(map[string]int64)
  269. hashes := make(map[string]int64)
  270. for _, u := range c.ClientURLs {
  271. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  272. if err != nil {
  273. return nil, nil, err
  274. }
  275. kvc := pb.NewKVClient(conn)
  276. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  277. resp, err := kvc.Hash(ctx, &pb.HashRequest{})
  278. cancel()
  279. conn.Close()
  280. if err != nil {
  281. return nil, nil, err
  282. }
  283. revs[u] = resp.Header.Revision
  284. hashes[u] = int64(resp.Hash)
  285. }
  286. return revs, hashes, nil
  287. }
  288. func (c *cluster) compactKV(rev int64) error {
  289. var (
  290. conn *grpc.ClientConn
  291. err error
  292. )
  293. for _, u := range c.ClientURLs {
  294. conn, err = grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  295. if err != nil {
  296. continue
  297. }
  298. kvc := pb.NewKVClient(conn)
  299. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  300. _, err = kvc.Compact(ctx, &pb.CompactionRequest{Revision: rev})
  301. cancel()
  302. conn.Close()
  303. if err == nil {
  304. return nil
  305. }
  306. }
  307. return err
  308. }