cluster.go 8.1 KB

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