etcd_client.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // Copyright 2019 Yunion
  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 informer
  15. import (
  16. "context"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/onecloud/pkg/cloudcommon/etcd"
  24. )
  25. type IWatcher interface {
  26. Watch(ctx context.Context, key string, handler ResourceEventHandler) error
  27. Unwatch(key string)
  28. }
  29. type ResourceEventHandler interface {
  30. OnAdd(obj *jsonutils.JSONDict)
  31. OnUpdate(oldObj, newObj *jsonutils.JSONDict)
  32. OnDelete(obj *jsonutils.JSONDict)
  33. }
  34. type EtcdBackendForClient struct {
  35. *EtcdBackend
  36. clientResources map[string]ResourceEventHandler
  37. }
  38. func NewEtcdBackendForClient(opt *etcd.SEtcdOptions) (*EtcdBackendForClient, error) {
  39. bec := &EtcdBackendForClient{
  40. clientResources: make(map[string]ResourceEventHandler, 0),
  41. }
  42. be, err := newEtcdBackend(opt, bec.onKeepaliveFailure)
  43. if err != nil {
  44. return nil, err
  45. }
  46. bec.EtcdBackend = be
  47. bec.StartClientWatch(context.Background())
  48. return bec, nil
  49. }
  50. func (b *EtcdBackendForClient) onKeepaliveFailure() {
  51. if err := b.client.RestartSession(); err != nil {
  52. log.Errorf("restart etcd session error: %v", err)
  53. return
  54. }
  55. b.StartClientWatch(context.Background())
  56. }
  57. func (b *EtcdBackendForClient) StartClientWatch(ctx context.Context) {
  58. wf := func(key string) string {
  59. return filepath.Join(EtcdInformerPrefix, key)
  60. }
  61. for key, handler := range b.clientResources {
  62. // if etcd pod deleted, should unwatch then rewatch resource
  63. b.Unwatch(key)
  64. if err := b.Watch(ctx, key, handler); err != nil {
  65. log.Errorf("start watch client resource %s error: %v", key, err)
  66. continue
  67. }
  68. log.Infof("%s rewatched", wf(key))
  69. }
  70. b.client.Unwatch("/")
  71. if err := b.client.Watch(ctx, "/", b.onClientResourceCreate, b.onClientResourceUpdate, b.onClientResourceDelete); err != nil {
  72. log.Errorf("start watch %s error: %v", wf("/"), err)
  73. } else {
  74. log.Infof("%s watched", wf("/"))
  75. }
  76. }
  77. func (b *EtcdBackend) getClientRegisterKey(resKey string) (string, error) {
  78. hostname, err := os.Hostname()
  79. if err != nil {
  80. return "", errors.Wrap(err, "get hostname")
  81. }
  82. clientKey := fmt.Sprintf("/%s/%s/%s", resKey, EtcdInformerClientsKey, hostname)
  83. return clientKey, nil
  84. }
  85. func (b *EtcdBackendForClient) registerClientResource(ctx context.Context, key string) error {
  86. clientKey, err := b.getClientRegisterKey(key)
  87. if err != nil {
  88. return err
  89. }
  90. if err := b.PutSession(ctx, clientKey, "ok"); err != nil {
  91. return err
  92. }
  93. return nil
  94. }
  95. func (b *EtcdBackendForClient) Watch(ctx context.Context, key string, handler ResourceEventHandler) error {
  96. b.clientResources[key] = handler
  97. if err := b.registerClientResource(ctx, key); err != nil {
  98. return errors.Wrapf(err, "register watch client resource %s", key)
  99. }
  100. return b.client.Watch(ctx, b.getWatchKey(key), b.onCreate(ctx, handler), b.onModify(ctx, handler), nil)
  101. }
  102. func (b *EtcdBackendForClient) Unwatch(key string) {
  103. delete(b.clientResources, key)
  104. b.client.Unwatch(b.getWatchKey(key))
  105. }
  106. func (b *EtcdBackendForClient) onCreate(ctx context.Context, handler ResourceEventHandler) etcd.TEtcdCreateEventFunc {
  107. return func(ctx context.Context, key, value []byte) {
  108. b.processEvent(handler, string(key), value)
  109. }
  110. }
  111. func (b *EtcdBackendForClient) onModify(ctx context.Context, handler ResourceEventHandler) etcd.TEtcdModifyEventFunc {
  112. return func(ctx context.Context, key, _, value []byte) {
  113. // not care about oldvalue, so ignore it
  114. b.processEvent(handler, string(key), value)
  115. }
  116. }
  117. func (b *EtcdBackendForClient) processEvent(handler ResourceEventHandler, key string, value []byte) {
  118. if len(value) == 0 {
  119. // object already deleted by lease out of ttl
  120. return
  121. }
  122. if b.isClientsKey([]byte(key)) {
  123. return
  124. }
  125. mObj, err := newModelObjectFromValue(value)
  126. if err != nil {
  127. log.Errorf("new %s model objecd from value error: %v", key, err)
  128. return
  129. }
  130. eType := mObj.EventType
  131. switch eType {
  132. case EventTypeCreate:
  133. handler.OnAdd(mObj.Object)
  134. case EventTypeUpdate:
  135. handler.OnUpdate(mObj.OldObject, mObj.Object)
  136. case EventTypeDelete:
  137. handler.OnDelete(mObj.Object)
  138. default:
  139. log.Errorf("Invalid key %s, event type: %s, mObj: %#v", key, eType, mObj)
  140. }
  141. }
  142. func (b *EtcdBackendForClient) onClientResourceAdd(key []byte) {
  143. // do nothing
  144. // self registered key has store in b.clientResources
  145. }
  146. func (b *EtcdBackendForClient) onClientResourceCreate(ctx context.Context, key, value []byte) {
  147. b.onClientResourceAdd(key)
  148. }
  149. func (b *EtcdBackendForClient) onClientResourceUpdate(ctx context.Context, key, oldvalue, value []byte) {
  150. b.onClientResourceAdd(key)
  151. }
  152. func (b *EtcdBackendForClient) onClientResourceDelete(ctx context.Context, key []byte) {
  153. if !b.isClientsKey(key) {
  154. return
  155. }
  156. keywordPlural, err := b.getClientWatchResource(key)
  157. if err != nil {
  158. log.Errorf("get client watch resource keywordPlural error: %v", err)
  159. return
  160. }
  161. _, ok := b.clientResources[keywordPlural]
  162. if !ok {
  163. return
  164. }
  165. if err := b.registerClientResource(ctx, keywordPlural); err != nil {
  166. log.Errorf("rewatch client resource %s error: %v", keywordPlural, err)
  167. return
  168. }
  169. }