registry.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package internal
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "git.i2edu.net/i2/go-zero/core/contextx"
  11. "git.i2edu.net/i2/go-zero/core/lang"
  12. "git.i2edu.net/i2/go-zero/core/logx"
  13. "git.i2edu.net/i2/go-zero/core/syncx"
  14. "git.i2edu.net/i2/go-zero/core/threading"
  15. "go.etcd.io/etcd/clientv3"
  16. )
  17. var (
  18. registry = Registry{
  19. clusters: make(map[string]*cluster),
  20. }
  21. connManager = syncx.NewResourceManager()
  22. )
  23. // A Registry is a registry that manages the etcd client connections.
  24. type Registry struct {
  25. clusters map[string]*cluster
  26. lock sync.Mutex
  27. }
  28. // GetRegistry returns a global Registry.
  29. func GetRegistry() *Registry {
  30. return &registry
  31. }
  32. // GetConn returns an etcd client connection associated with given endpoints.
  33. func (r *Registry) GetConn(endpoints []string) (EtcdClient, error) {
  34. return r.getCluster(endpoints).getClient()
  35. }
  36. // Monitor monitors the key on given etcd endpoints, notify with the given UpdateListener.
  37. func (r *Registry) Monitor(endpoints []string, key string, l UpdateListener) error {
  38. return r.getCluster(endpoints).monitor(key, l)
  39. }
  40. func (r *Registry) getCluster(endpoints []string) *cluster {
  41. clusterKey := getClusterKey(endpoints)
  42. r.lock.Lock()
  43. defer r.lock.Unlock()
  44. c, ok := r.clusters[clusterKey]
  45. if !ok {
  46. c = newCluster(endpoints)
  47. r.clusters[clusterKey] = c
  48. }
  49. return c
  50. }
  51. type cluster struct {
  52. endpoints []string
  53. key string
  54. values map[string]map[string]string
  55. listeners map[string][]UpdateListener
  56. watchGroup *threading.RoutineGroup
  57. done chan lang.PlaceholderType
  58. lock sync.Mutex
  59. }
  60. func newCluster(endpoints []string) *cluster {
  61. return &cluster{
  62. endpoints: endpoints,
  63. key: getClusterKey(endpoints),
  64. values: make(map[string]map[string]string),
  65. listeners: make(map[string][]UpdateListener),
  66. watchGroup: threading.NewRoutineGroup(),
  67. done: make(chan lang.PlaceholderType),
  68. }
  69. }
  70. func (c *cluster) context(cli EtcdClient) context.Context {
  71. return contextx.ValueOnlyFrom(cli.Ctx())
  72. }
  73. func (c *cluster) getClient() (EtcdClient, error) {
  74. val, err := connManager.GetResource(c.key, func() (io.Closer, error) {
  75. return c.newClient()
  76. })
  77. if err != nil {
  78. return nil, err
  79. }
  80. return val.(EtcdClient), nil
  81. }
  82. func (c *cluster) handleChanges(key string, kvs []KV) {
  83. var add []KV
  84. var remove []KV
  85. c.lock.Lock()
  86. listeners := append([]UpdateListener(nil), c.listeners[key]...)
  87. vals, ok := c.values[key]
  88. if !ok {
  89. add = kvs
  90. vals = make(map[string]string)
  91. for _, kv := range kvs {
  92. vals[kv.Key] = kv.Val
  93. }
  94. c.values[key] = vals
  95. } else {
  96. m := make(map[string]string)
  97. for _, kv := range kvs {
  98. m[kv.Key] = kv.Val
  99. }
  100. for k, v := range vals {
  101. if val, ok := m[k]; !ok || v != val {
  102. remove = append(remove, KV{
  103. Key: k,
  104. Val: v,
  105. })
  106. }
  107. }
  108. for k, v := range m {
  109. if val, ok := vals[k]; !ok || v != val {
  110. add = append(add, KV{
  111. Key: k,
  112. Val: v,
  113. })
  114. }
  115. }
  116. c.values[key] = m
  117. }
  118. c.lock.Unlock()
  119. for _, kv := range add {
  120. for _, l := range listeners {
  121. l.OnAdd(kv)
  122. }
  123. }
  124. for _, kv := range remove {
  125. for _, l := range listeners {
  126. l.OnDelete(kv)
  127. }
  128. }
  129. }
  130. func (c *cluster) handleWatchEvents(key string, events []*clientv3.Event) {
  131. c.lock.Lock()
  132. listeners := append([]UpdateListener(nil), c.listeners[key]...)
  133. c.lock.Unlock()
  134. for _, ev := range events {
  135. switch ev.Type {
  136. case clientv3.EventTypePut:
  137. c.lock.Lock()
  138. if vals, ok := c.values[key]; ok {
  139. vals[string(ev.Kv.Key)] = string(ev.Kv.Value)
  140. } else {
  141. c.values[key] = map[string]string{string(ev.Kv.Key): string(ev.Kv.Value)}
  142. }
  143. c.lock.Unlock()
  144. for _, l := range listeners {
  145. l.OnAdd(KV{
  146. Key: string(ev.Kv.Key),
  147. Val: string(ev.Kv.Value),
  148. })
  149. }
  150. case clientv3.EventTypeDelete:
  151. if vals, ok := c.values[key]; ok {
  152. delete(vals, string(ev.Kv.Key))
  153. }
  154. for _, l := range listeners {
  155. l.OnDelete(KV{
  156. Key: string(ev.Kv.Key),
  157. Val: string(ev.Kv.Value),
  158. })
  159. }
  160. default:
  161. logx.Errorf("Unknown event type: %v", ev.Type)
  162. }
  163. }
  164. }
  165. func (c *cluster) load(cli EtcdClient, key string) {
  166. var resp *clientv3.GetResponse
  167. for {
  168. var err error
  169. ctx, cancel := context.WithTimeout(c.context(cli), RequestTimeout)
  170. resp, err = cli.Get(ctx, makeKeyPrefix(key), clientv3.WithPrefix())
  171. cancel()
  172. if err == nil {
  173. break
  174. }
  175. logx.Error(err)
  176. time.Sleep(coolDownInterval)
  177. }
  178. var kvs []KV
  179. c.lock.Lock()
  180. for _, ev := range resp.Kvs {
  181. kvs = append(kvs, KV{
  182. Key: string(ev.Key),
  183. Val: string(ev.Value),
  184. })
  185. }
  186. c.lock.Unlock()
  187. c.handleChanges(key, kvs)
  188. }
  189. func (c *cluster) monitor(key string, l UpdateListener) error {
  190. c.lock.Lock()
  191. c.listeners[key] = append(c.listeners[key], l)
  192. c.lock.Unlock()
  193. cli, err := c.getClient()
  194. if err != nil {
  195. return err
  196. }
  197. c.load(cli, key)
  198. c.watchGroup.Run(func() {
  199. c.watch(cli, key)
  200. })
  201. return nil
  202. }
  203. func (c *cluster) newClient() (EtcdClient, error) {
  204. cli, err := NewClient(c.endpoints)
  205. if err != nil {
  206. return nil, err
  207. }
  208. go c.watchConnState(cli)
  209. return cli, nil
  210. }
  211. func (c *cluster) reload(cli EtcdClient) {
  212. c.lock.Lock()
  213. close(c.done)
  214. c.watchGroup.Wait()
  215. c.done = make(chan lang.PlaceholderType)
  216. c.watchGroup = threading.NewRoutineGroup()
  217. var keys []string
  218. for k := range c.listeners {
  219. keys = append(keys, k)
  220. }
  221. c.lock.Unlock()
  222. for _, key := range keys {
  223. k := key
  224. c.watchGroup.Run(func() {
  225. c.load(cli, k)
  226. c.watch(cli, k)
  227. })
  228. }
  229. }
  230. func (c *cluster) watch(cli EtcdClient, key string) {
  231. rch := cli.Watch(clientv3.WithRequireLeader(c.context(cli)), makeKeyPrefix(key), clientv3.WithPrefix())
  232. for {
  233. select {
  234. case wresp, ok := <-rch:
  235. if !ok {
  236. logx.Error("etcd monitor chan has been closed")
  237. return
  238. }
  239. if wresp.Canceled {
  240. logx.Error("etcd monitor chan has been canceled")
  241. return
  242. }
  243. if wresp.Err() != nil {
  244. logx.Error(fmt.Sprintf("etcd monitor chan error: %v", wresp.Err()))
  245. return
  246. }
  247. c.handleWatchEvents(key, wresp.Events)
  248. case <-c.done:
  249. return
  250. }
  251. }
  252. }
  253. func (c *cluster) watchConnState(cli EtcdClient) {
  254. watcher := newStateWatcher()
  255. watcher.addListener(func() {
  256. go c.reload(cli)
  257. })
  258. watcher.watch(cli.ActiveConnection())
  259. }
  260. // DialClient dials an etcd cluster with given endpoints.
  261. func DialClient(endpoints []string) (EtcdClient, error) {
  262. return clientv3.New(clientv3.Config{
  263. Endpoints: endpoints,
  264. AutoSyncInterval: autoSyncInterval,
  265. DialTimeout: DialTimeout,
  266. DialKeepAliveTime: dialKeepAliveTime,
  267. DialKeepAliveTimeout: DialTimeout,
  268. RejectOldCluster: true,
  269. })
  270. }
  271. func getClusterKey(endpoints []string) string {
  272. sort.Strings(endpoints)
  273. return strings.Join(endpoints, endpointsSeparator)
  274. }
  275. func makeKeyPrefix(key string) string {
  276. return fmt.Sprintf("%s%c", key, Delimiter)
  277. }