cluster.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. "golang.org/x/net/context"
  22. "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. grpcURLs[i] = fmt.Sprintf("%s:2379", host)
  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. }
  100. if _, err := a.Start(flags...); err != nil {
  101. // cleanup
  102. for j := 0; j < i; j++ {
  103. agents[j].Terminate()
  104. }
  105. return err
  106. }
  107. }
  108. // TODO: Too intensive stressers can panic etcd member with
  109. // 'out of memory' error. Put rate limits in server side.
  110. stressN := 100
  111. var stressers []Stresser
  112. if c.v2Only {
  113. for _, u := range clientURLs {
  114. s := &stresserV2{
  115. Endpoint: u,
  116. KeySize: c.stressKeySize,
  117. KeySuffixRange: c.stressKeySuffixRange,
  118. N: stressN,
  119. }
  120. go s.Stress()
  121. stressers = append(stressers, s)
  122. }
  123. } else {
  124. for _, u := range grpcURLs {
  125. s := &stresser{
  126. Endpoint: u,
  127. KeySize: c.stressKeySize,
  128. KeySuffixRange: c.stressKeySuffixRange,
  129. N: stressN,
  130. }
  131. go s.Stress()
  132. stressers = append(stressers, s)
  133. }
  134. }
  135. c.Size = size
  136. c.Agents = agents
  137. c.Stressers = stressers
  138. c.Names = names
  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.ClientURLs
  149. if c.v2Only {
  150. healthFunc, urls = setHealthKeyV2, c.ClientURLs
  151. }
  152. for i := 0; i < 60; i++ {
  153. err = healthFunc(urls)
  154. if err == nil {
  155. return nil
  156. }
  157. time.Sleep(time.Second)
  158. }
  159. return err
  160. }
  161. // GetLeader returns the index of leader and error if any.
  162. func (c *cluster) GetLeader() (int, error) {
  163. if c.v2Only {
  164. return 0, nil
  165. }
  166. cli, err := clientv3.New(clientv3.Config{
  167. Endpoints: c.ClientURLs,
  168. DialTimeout: 5 * time.Second,
  169. })
  170. if err != nil {
  171. return 0, err
  172. }
  173. defer cli.Close()
  174. clus := clientv3.NewCluster(cli)
  175. mem, err := clus.MemberLeader(context.Background())
  176. if err != nil {
  177. return 0, err
  178. }
  179. for i, name := range c.Names {
  180. if name == mem.Name {
  181. return i, nil
  182. }
  183. }
  184. return 0, fmt.Errorf("no leader found")
  185. }
  186. func (c *cluster) Report() (success, failure int) {
  187. for _, stress := range c.Stressers {
  188. s, f := stress.Report()
  189. success += s
  190. failure += f
  191. }
  192. return
  193. }
  194. func (c *cluster) Cleanup() error {
  195. var lasterr error
  196. for _, a := range c.Agents {
  197. if err := a.Cleanup(); err != nil {
  198. lasterr = err
  199. }
  200. }
  201. for _, s := range c.Stressers {
  202. s.Cancel()
  203. }
  204. return lasterr
  205. }
  206. func (c *cluster) Terminate() {
  207. for _, a := range c.Agents {
  208. a.Terminate()
  209. }
  210. for _, s := range c.Stressers {
  211. s.Cancel()
  212. }
  213. }
  214. func (c *cluster) Status() ClusterStatus {
  215. cs := ClusterStatus{
  216. AgentStatuses: make(map[string]client.Status),
  217. }
  218. for i, a := range c.Agents {
  219. s, err := a.Status()
  220. // TODO: add a.Desc() as a key of the map
  221. desc := c.agentEndpoints[i]
  222. if err != nil {
  223. cs.AgentStatuses[desc] = client.Status{State: "unknown"}
  224. plog.Printf("failed to get the status of agent [%s]", desc)
  225. }
  226. cs.AgentStatuses[desc] = s
  227. }
  228. return cs
  229. }
  230. // setHealthKey sets health key on all given urls.
  231. func setHealthKey(us []string) error {
  232. for _, u := range us {
  233. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  234. if err != nil {
  235. return fmt.Errorf("%v (%s)", err, u)
  236. }
  237. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  238. kvc := pb.NewKVClient(conn)
  239. _, err = kvc.Put(ctx, &pb.PutRequest{Key: []byte("health"), Value: []byte("good")})
  240. cancel()
  241. conn.Close()
  242. if err != nil {
  243. return err
  244. }
  245. }
  246. return nil
  247. }
  248. // setHealthKeyV2 sets health key on all given urls.
  249. func setHealthKeyV2(us []string) error {
  250. for _, u := range us {
  251. cfg := clientv2.Config{
  252. Endpoints: []string{u},
  253. }
  254. c, err := clientv2.New(cfg)
  255. if err != nil {
  256. return err
  257. }
  258. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  259. kapi := clientv2.NewKeysAPI(c)
  260. _, err = kapi.Set(ctx, "health", "good", nil)
  261. cancel()
  262. if err != nil {
  263. return err
  264. }
  265. }
  266. return nil
  267. }
  268. func (c *cluster) getRevisionHash() (map[string]int64, map[string]int64, error) {
  269. revs := make(map[string]int64)
  270. hashes := make(map[string]int64)
  271. for _, u := range c.ClientURLs {
  272. conn, err := grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  273. if err != nil {
  274. return nil, nil, err
  275. }
  276. kvc := pb.NewKVClient(conn)
  277. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  278. resp, err := kvc.Hash(ctx, &pb.HashRequest{})
  279. cancel()
  280. conn.Close()
  281. if err != nil {
  282. return nil, nil, err
  283. }
  284. revs[u] = resp.Header.Revision
  285. hashes[u] = int64(resp.Hash)
  286. }
  287. return revs, hashes, nil
  288. }
  289. func (c *cluster) compactKV(rev int64) error {
  290. var (
  291. conn *grpc.ClientConn
  292. err error
  293. )
  294. for _, u := range c.ClientURLs {
  295. conn, err = grpc.Dial(u, grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))
  296. if err != nil {
  297. continue
  298. }
  299. kvc := pb.NewKVClient(conn)
  300. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  301. _, err = kvc.Compact(ctx, &pb.CompactionRequest{Revision: rev})
  302. cancel()
  303. conn.Close()
  304. if err == nil {
  305. return nil
  306. }
  307. }
  308. return err
  309. }