cluster.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Copyright 2016 The etcd Authors
  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 grpcproxy
  15. import (
  16. "fmt"
  17. "os"
  18. "sync"
  19. "github.com/coreos/etcd/clientv3"
  20. "github.com/coreos/etcd/clientv3/naming"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "golang.org/x/net/context"
  23. "golang.org/x/time/rate"
  24. "google.golang.org/grpc"
  25. gnaming "google.golang.org/grpc/naming"
  26. )
  27. // allow maximum 1 retry per second
  28. const resolveRetryRate = 1
  29. type clusterProxy struct {
  30. clus clientv3.Cluster
  31. ctx context.Context
  32. gr *naming.GRPCResolver
  33. // advertise client URL
  34. advaddr string
  35. prefix string
  36. umu sync.RWMutex
  37. umap map[string]gnaming.Update
  38. }
  39. // NewClusterProxy takes optional prefix to fetch grpc-proxy member endpoints.
  40. // The returned channel is closed when there is grpc-proxy endpoint registered
  41. // and the client's context is canceled so the 'register' loop returns.
  42. func NewClusterProxy(c *clientv3.Client, advaddr string, prefix string) (pb.ClusterServer, <-chan struct{}) {
  43. cp := &clusterProxy{
  44. clus: c.Cluster,
  45. ctx: c.Ctx(),
  46. gr: &naming.GRPCResolver{Client: c},
  47. advaddr: advaddr,
  48. prefix: prefix,
  49. umap: make(map[string]gnaming.Update),
  50. }
  51. donec := make(chan struct{})
  52. if advaddr != "" && prefix != "" {
  53. go func() {
  54. defer close(donec)
  55. cp.resolve(prefix)
  56. }()
  57. return cp, donec
  58. }
  59. close(donec)
  60. return cp, donec
  61. }
  62. func (cp *clusterProxy) resolve(prefix string) {
  63. rm := rate.NewLimiter(rate.Limit(resolveRetryRate), resolveRetryRate)
  64. for rm.Wait(cp.ctx) == nil {
  65. wa, err := cp.gr.Resolve(prefix)
  66. if err != nil {
  67. plog.Warningf("failed to resolve %q (%v)", prefix, err)
  68. continue
  69. }
  70. cp.monitor(wa)
  71. }
  72. }
  73. func (cp *clusterProxy) monitor(wa gnaming.Watcher) {
  74. for cp.ctx.Err() == nil {
  75. ups, err := wa.Next()
  76. if err != nil {
  77. plog.Warningf("clusterProxy watcher error (%v)", err)
  78. if grpc.ErrorDesc(err) == naming.ErrWatcherClosed.Error() {
  79. return
  80. }
  81. }
  82. cp.umu.Lock()
  83. for i := range ups {
  84. switch ups[i].Op {
  85. case gnaming.Add:
  86. cp.umap[ups[i].Addr] = *ups[i]
  87. case gnaming.Delete:
  88. delete(cp.umap, ups[i].Addr)
  89. }
  90. }
  91. cp.umu.Unlock()
  92. }
  93. }
  94. func (cp *clusterProxy) MemberAdd(ctx context.Context, r *pb.MemberAddRequest) (*pb.MemberAddResponse, error) {
  95. mresp, err := cp.clus.MemberAdd(ctx, r.PeerURLs)
  96. if err != nil {
  97. return nil, err
  98. }
  99. resp := (pb.MemberAddResponse)(*mresp)
  100. return &resp, err
  101. }
  102. func (cp *clusterProxy) MemberRemove(ctx context.Context, r *pb.MemberRemoveRequest) (*pb.MemberRemoveResponse, error) {
  103. mresp, err := cp.clus.MemberRemove(ctx, r.ID)
  104. if err != nil {
  105. return nil, err
  106. }
  107. resp := (pb.MemberRemoveResponse)(*mresp)
  108. return &resp, err
  109. }
  110. func (cp *clusterProxy) MemberUpdate(ctx context.Context, r *pb.MemberUpdateRequest) (*pb.MemberUpdateResponse, error) {
  111. mresp, err := cp.clus.MemberUpdate(ctx, r.ID, r.PeerURLs)
  112. if err != nil {
  113. return nil, err
  114. }
  115. resp := (pb.MemberUpdateResponse)(*mresp)
  116. return &resp, err
  117. }
  118. func (cp *clusterProxy) membersFromUpdates() ([]*pb.Member, error) {
  119. cp.umu.RLock()
  120. defer cp.umu.RUnlock()
  121. mbs := make([]*pb.Member, 0, len(cp.umap))
  122. for addr, upt := range cp.umap {
  123. m, err := decodeMeta(fmt.Sprint(upt.Metadata))
  124. if err != nil {
  125. return nil, err
  126. }
  127. mbs = append(mbs, &pb.Member{Name: m.Name, ClientURLs: []string{addr}})
  128. }
  129. return mbs, nil
  130. }
  131. // MemberList wraps member list API with following rules:
  132. // - If 'advaddr' is not empty and 'prefix' is not empty, return registered member lists via resolver
  133. // - If 'advaddr' is not empty and 'prefix' is not empty and registered grpc-proxy members haven't been fetched, return the 'advaddr'
  134. // - If 'advaddr' is not empty and 'prefix' is empty, return 'advaddr' without forcing it to 'register'
  135. // - If 'advaddr' is empty, forward to member list API
  136. func (cp *clusterProxy) MemberList(ctx context.Context, r *pb.MemberListRequest) (*pb.MemberListResponse, error) {
  137. if cp.advaddr != "" {
  138. if cp.prefix != "" {
  139. mbs, err := cp.membersFromUpdates()
  140. if err != nil {
  141. return nil, err
  142. }
  143. if len(mbs) > 0 {
  144. return &pb.MemberListResponse{Members: mbs}, nil
  145. }
  146. }
  147. // prefix is empty or no grpc-proxy members haven't been registered
  148. hostname, _ := os.Hostname()
  149. return &pb.MemberListResponse{Members: []*pb.Member{{Name: hostname, ClientURLs: []string{cp.advaddr}}}}, nil
  150. }
  151. mresp, err := cp.clus.MemberList(ctx)
  152. if err != nil {
  153. return nil, err
  154. }
  155. resp := (pb.MemberListResponse)(*mresp)
  156. return &resp, err
  157. }