registry.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. package internal
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/wuntsong-org/go-zero-plus/core/contextx"
  11. "github.com/wuntsong-org/go-zero-plus/core/lang"
  12. "github.com/wuntsong-org/go-zero-plus/core/logx"
  13. "github.com/wuntsong-org/go-zero-plus/core/syncx"
  14. "github.com/wuntsong-org/go-zero-plus/core/threading"
  15. clientv3 "go.etcd.io/etcd/client/v3"
  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. c, _ := r.getCluster(endpoints)
  35. return c.getClient()
  36. }
  37. // Monitor monitors the key on given etcd endpoints, notify with the given UpdateListener.
  38. func (r *Registry) Monitor(endpoints []string, key string, l UpdateListener) error {
  39. c, exists := r.getCluster(endpoints)
  40. // if exists, the existing values should be updated to the listener.
  41. if exists {
  42. kvs := c.getCurrent(key)
  43. for _, kv := range kvs {
  44. l.OnAdd(kv)
  45. }
  46. }
  47. return c.monitor(key, l)
  48. }
  49. func (r *Registry) getCluster(endpoints []string) (c *cluster, exists bool) {
  50. clusterKey := getClusterKey(endpoints)
  51. r.lock.Lock()
  52. defer r.lock.Unlock()
  53. c, exists = r.clusters[clusterKey]
  54. if !exists {
  55. c = newCluster(endpoints)
  56. r.clusters[clusterKey] = c
  57. }
  58. return
  59. }
  60. type cluster struct {
  61. endpoints []string
  62. key string
  63. values map[string]map[string]string
  64. listeners map[string][]UpdateListener
  65. watchGroup *threading.RoutineGroup
  66. done chan lang.PlaceholderType
  67. lock sync.Mutex
  68. }
  69. func newCluster(endpoints []string) *cluster {
  70. return &cluster{
  71. endpoints: endpoints,
  72. key: getClusterKey(endpoints),
  73. values: make(map[string]map[string]string),
  74. listeners: make(map[string][]UpdateListener),
  75. watchGroup: threading.NewRoutineGroup(),
  76. done: make(chan lang.PlaceholderType),
  77. }
  78. }
  79. func (c *cluster) context(cli EtcdClient) context.Context {
  80. return contextx.ValueOnlyFrom(cli.Ctx())
  81. }
  82. func (c *cluster) getClient() (EtcdClient, error) {
  83. val, err := connManager.GetResource(c.key, func() (io.Closer, error) {
  84. return c.newClient()
  85. })
  86. if err != nil {
  87. return nil, err
  88. }
  89. return val.(EtcdClient), nil
  90. }
  91. func (c *cluster) getCurrent(key string) []KV {
  92. c.lock.Lock()
  93. defer c.lock.Unlock()
  94. var kvs []KV
  95. for k, v := range c.values[key] {
  96. kvs = append(kvs, KV{
  97. Key: k,
  98. Val: v,
  99. })
  100. }
  101. return kvs
  102. }
  103. func (c *cluster) handleChanges(key string, kvs []KV) {
  104. var add []KV
  105. var remove []KV
  106. c.lock.Lock()
  107. listeners := append([]UpdateListener(nil), c.listeners[key]...)
  108. vals, ok := c.values[key]
  109. if !ok {
  110. add = kvs
  111. vals = make(map[string]string)
  112. for _, kv := range kvs {
  113. vals[kv.Key] = kv.Val
  114. }
  115. c.values[key] = vals
  116. } else {
  117. m := make(map[string]string)
  118. for _, kv := range kvs {
  119. m[kv.Key] = kv.Val
  120. }
  121. for k, v := range vals {
  122. if val, ok := m[k]; !ok || v != val {
  123. remove = append(remove, KV{
  124. Key: k,
  125. Val: v,
  126. })
  127. }
  128. }
  129. for k, v := range m {
  130. if val, ok := vals[k]; !ok || v != val {
  131. add = append(add, KV{
  132. Key: k,
  133. Val: v,
  134. })
  135. }
  136. }
  137. c.values[key] = m
  138. }
  139. c.lock.Unlock()
  140. for _, kv := range add {
  141. for _, l := range listeners {
  142. l.OnAdd(kv)
  143. }
  144. }
  145. for _, kv := range remove {
  146. for _, l := range listeners {
  147. l.OnDelete(kv)
  148. }
  149. }
  150. }
  151. func (c *cluster) handleWatchEvents(key string, events []*clientv3.Event) {
  152. c.lock.Lock()
  153. listeners := append([]UpdateListener(nil), c.listeners[key]...)
  154. c.lock.Unlock()
  155. for _, ev := range events {
  156. switch ev.Type {
  157. case clientv3.EventTypePut:
  158. c.lock.Lock()
  159. if vals, ok := c.values[key]; ok {
  160. vals[string(ev.Kv.Key)] = string(ev.Kv.Value)
  161. } else {
  162. c.values[key] = map[string]string{string(ev.Kv.Key): string(ev.Kv.Value)}
  163. }
  164. c.lock.Unlock()
  165. for _, l := range listeners {
  166. l.OnAdd(KV{
  167. Key: string(ev.Kv.Key),
  168. Val: string(ev.Kv.Value),
  169. })
  170. }
  171. case clientv3.EventTypeDelete:
  172. c.lock.Lock()
  173. if vals, ok := c.values[key]; ok {
  174. delete(vals, string(ev.Kv.Key))
  175. }
  176. c.lock.Unlock()
  177. for _, l := range listeners {
  178. l.OnDelete(KV{
  179. Key: string(ev.Kv.Key),
  180. Val: string(ev.Kv.Value),
  181. })
  182. }
  183. default:
  184. logx.Errorf("Unknown event type: %v", ev.Type)
  185. }
  186. }
  187. }
  188. func (c *cluster) load(cli EtcdClient, key string) int64 {
  189. var resp *clientv3.GetResponse
  190. for {
  191. var err error
  192. ctx, cancel := context.WithTimeout(c.context(cli), RequestTimeout)
  193. resp, err = cli.Get(ctx, makeKeyPrefix(key), clientv3.WithPrefix())
  194. cancel()
  195. if err == nil {
  196. break
  197. }
  198. logx.Error(err)
  199. time.Sleep(coolDownInterval)
  200. }
  201. var kvs []KV
  202. for _, ev := range resp.Kvs {
  203. kvs = append(kvs, KV{
  204. Key: string(ev.Key),
  205. Val: string(ev.Value),
  206. })
  207. }
  208. c.handleChanges(key, kvs)
  209. return resp.Header.Revision
  210. }
  211. func (c *cluster) monitor(key string, l UpdateListener) error {
  212. c.lock.Lock()
  213. c.listeners[key] = append(c.listeners[key], l)
  214. c.lock.Unlock()
  215. cli, err := c.getClient()
  216. if err != nil {
  217. return err
  218. }
  219. rev := c.load(cli, key)
  220. c.watchGroup.Run(func() {
  221. c.watch(cli, key, rev)
  222. })
  223. return nil
  224. }
  225. func (c *cluster) newClient() (EtcdClient, error) {
  226. cli, err := NewClient(c.endpoints)
  227. if err != nil {
  228. return nil, err
  229. }
  230. go c.watchConnState(cli)
  231. return cli, nil
  232. }
  233. func (c *cluster) reload(cli EtcdClient) {
  234. c.lock.Lock()
  235. close(c.done)
  236. c.watchGroup.Wait()
  237. c.done = make(chan lang.PlaceholderType)
  238. c.watchGroup = threading.NewRoutineGroup()
  239. var keys []string
  240. for k := range c.listeners {
  241. keys = append(keys, k)
  242. }
  243. c.lock.Unlock()
  244. for _, key := range keys {
  245. k := key
  246. c.watchGroup.Run(func() {
  247. rev := c.load(cli, k)
  248. c.watch(cli, k, rev)
  249. })
  250. }
  251. }
  252. func (c *cluster) watch(cli EtcdClient, key string, rev int64) {
  253. for {
  254. if c.watchStream(cli, key, rev) {
  255. return
  256. }
  257. }
  258. }
  259. func (c *cluster) watchStream(cli EtcdClient, key string, rev int64) bool {
  260. var rch clientv3.WatchChan
  261. if rev != 0 {
  262. rch = cli.Watch(clientv3.WithRequireLeader(c.context(cli)), makeKeyPrefix(key), clientv3.WithPrefix(),
  263. clientv3.WithRev(rev+1))
  264. } else {
  265. rch = cli.Watch(clientv3.WithRequireLeader(c.context(cli)), makeKeyPrefix(key), clientv3.WithPrefix())
  266. }
  267. for {
  268. select {
  269. case wresp, ok := <-rch:
  270. if !ok {
  271. logx.Error("etcd monitor chan has been closed")
  272. return false
  273. }
  274. if wresp.Canceled {
  275. logx.Errorf("etcd monitor chan has been canceled, error: %v", wresp.Err())
  276. return false
  277. }
  278. if wresp.Err() != nil {
  279. logx.Error(fmt.Sprintf("etcd monitor chan error: %v", wresp.Err()))
  280. return false
  281. }
  282. c.handleWatchEvents(key, wresp.Events)
  283. case <-c.done:
  284. return true
  285. }
  286. }
  287. }
  288. func (c *cluster) watchConnState(cli EtcdClient) {
  289. watcher := newStateWatcher()
  290. watcher.addListener(func() {
  291. go c.reload(cli)
  292. })
  293. watcher.watch(cli.ActiveConnection())
  294. }
  295. // DialClient dials an etcd cluster with given endpoints.
  296. func DialClient(endpoints []string) (EtcdClient, error) {
  297. cfg := clientv3.Config{
  298. Endpoints: endpoints,
  299. AutoSyncInterval: autoSyncInterval,
  300. DialTimeout: DialTimeout,
  301. RejectOldCluster: true,
  302. PermitWithoutStream: true,
  303. }
  304. if account, ok := GetAccount(endpoints); ok {
  305. cfg.Username = account.User
  306. cfg.Password = account.Pass
  307. }
  308. if tlsCfg, ok := GetTLS(endpoints); ok {
  309. cfg.TLS = tlsCfg
  310. }
  311. return clientv3.New(cfg)
  312. }
  313. func getClusterKey(endpoints []string) string {
  314. sort.Strings(endpoints)
  315. return strings.Join(endpoints, endpointsSeparator)
  316. }
  317. func makeKeyPrefix(key string) string {
  318. return fmt.Sprintf("%s%c", key, Delimiter)
  319. }