watch.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "sync"
  17. "golang.org/x/net/context"
  18. "google.golang.org/grpc"
  19. "google.golang.org/grpc/metadata"
  20. "github.com/coreos/etcd/clientv3"
  21. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  22. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  23. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  24. )
  25. type watchProxy struct {
  26. cw clientv3.Watcher
  27. ctx context.Context
  28. leader *leader
  29. ranges *watchRanges
  30. // mu protects adding outstanding watch servers through wg.
  31. mu sync.Mutex
  32. // wg waits until all outstanding watch servers quit.
  33. wg sync.WaitGroup
  34. }
  35. func NewWatchProxy(c *clientv3.Client) (pb.WatchServer, <-chan struct{}) {
  36. cctx, cancel := context.WithCancel(c.Ctx())
  37. wp := &watchProxy{
  38. cw: c.Watcher,
  39. ctx: cctx,
  40. leader: newLeader(c.Ctx(), c.Watcher),
  41. }
  42. wp.ranges = newWatchRanges(wp)
  43. ch := make(chan struct{})
  44. go func() {
  45. defer close(ch)
  46. <-wp.leader.stopNotify()
  47. wp.mu.Lock()
  48. select {
  49. case <-wp.ctx.Done():
  50. case <-wp.leader.disconnectNotify():
  51. cancel()
  52. }
  53. <-wp.ctx.Done()
  54. wp.mu.Unlock()
  55. wp.wg.Wait()
  56. wp.ranges.stop()
  57. }()
  58. return wp, ch
  59. }
  60. func (wp *watchProxy) Watch(stream pb.Watch_WatchServer) (err error) {
  61. wp.mu.Lock()
  62. select {
  63. case <-wp.ctx.Done():
  64. wp.mu.Unlock()
  65. select {
  66. case <-wp.leader.disconnectNotify():
  67. return grpc.ErrClientConnClosing
  68. default:
  69. return wp.ctx.Err()
  70. }
  71. default:
  72. wp.wg.Add(1)
  73. }
  74. wp.mu.Unlock()
  75. ctx, cancel := context.WithCancel(stream.Context())
  76. wps := &watchProxyStream{
  77. ranges: wp.ranges,
  78. watchers: make(map[int64]*watcher),
  79. stream: stream,
  80. watchCh: make(chan *pb.WatchResponse, 1024),
  81. ctx: ctx,
  82. cancel: cancel,
  83. }
  84. var lostLeaderC <-chan struct{}
  85. if md, ok := metadata.FromOutgoingContext(stream.Context()); ok {
  86. v := md[rpctypes.MetadataRequireLeaderKey]
  87. if len(v) > 0 && v[0] == rpctypes.MetadataHasLeader {
  88. lostLeaderC = wp.leader.lostNotify()
  89. // if leader is known to be lost at creation time, avoid
  90. // letting events through at all
  91. select {
  92. case <-lostLeaderC:
  93. wp.wg.Done()
  94. return rpctypes.ErrNoLeader
  95. default:
  96. }
  97. }
  98. }
  99. // post to stopc => terminate server stream; can't use a waitgroup
  100. // since all goroutines will only terminate after Watch() exits.
  101. stopc := make(chan struct{}, 3)
  102. go func() {
  103. defer func() { stopc <- struct{}{} }()
  104. wps.recvLoop()
  105. }()
  106. go func() {
  107. defer func() { stopc <- struct{}{} }()
  108. wps.sendLoop()
  109. }()
  110. // tear down watch if leader goes down or entire watch proxy is terminated
  111. go func() {
  112. defer func() { stopc <- struct{}{} }()
  113. select {
  114. case <-lostLeaderC:
  115. case <-ctx.Done():
  116. case <-wp.ctx.Done():
  117. }
  118. }()
  119. <-stopc
  120. cancel()
  121. // recv/send may only shutdown after function exits;
  122. // goroutine notifies proxy that stream is through
  123. go func() {
  124. <-stopc
  125. <-stopc
  126. wps.close()
  127. wp.wg.Done()
  128. }()
  129. select {
  130. case <-lostLeaderC:
  131. return rpctypes.ErrNoLeader
  132. case <-wp.leader.disconnectNotify():
  133. return grpc.ErrClientConnClosing
  134. default:
  135. return wps.ctx.Err()
  136. }
  137. }
  138. // watchProxyStream forwards etcd watch events to a proxied client stream.
  139. type watchProxyStream struct {
  140. ranges *watchRanges
  141. // mu protects watchers and nextWatcherID
  142. mu sync.Mutex
  143. // watchers receive events from watch broadcast.
  144. watchers map[int64]*watcher
  145. // nextWatcherID is the id to assign the next watcher on this stream.
  146. nextWatcherID int64
  147. stream pb.Watch_WatchServer
  148. // watchCh receives watch responses from the watchers.
  149. watchCh chan *pb.WatchResponse
  150. ctx context.Context
  151. cancel context.CancelFunc
  152. }
  153. func (wps *watchProxyStream) close() {
  154. var wg sync.WaitGroup
  155. wps.cancel()
  156. wps.mu.Lock()
  157. wg.Add(len(wps.watchers))
  158. for _, wpsw := range wps.watchers {
  159. go func(w *watcher) {
  160. wps.ranges.delete(w)
  161. wg.Done()
  162. }(wpsw)
  163. }
  164. wps.watchers = nil
  165. wps.mu.Unlock()
  166. wg.Wait()
  167. close(wps.watchCh)
  168. }
  169. func (wps *watchProxyStream) recvLoop() error {
  170. for {
  171. req, err := wps.stream.Recv()
  172. if err != nil {
  173. return err
  174. }
  175. switch uv := req.RequestUnion.(type) {
  176. case *pb.WatchRequest_CreateRequest:
  177. cr := uv.CreateRequest
  178. w := &watcher{
  179. wr: watchRange{string(cr.Key), string(cr.RangeEnd)},
  180. id: wps.nextWatcherID,
  181. wps: wps,
  182. nextrev: cr.StartRevision,
  183. progress: cr.ProgressNotify,
  184. prevKV: cr.PrevKv,
  185. filters: v3rpc.FiltersFromRequest(cr),
  186. }
  187. if !w.wr.valid() {
  188. w.post(&pb.WatchResponse{WatchId: -1, Created: true, Canceled: true})
  189. continue
  190. }
  191. wps.nextWatcherID++
  192. w.nextrev = cr.StartRevision
  193. wps.watchers[w.id] = w
  194. wps.ranges.add(w)
  195. case *pb.WatchRequest_CancelRequest:
  196. wps.delete(uv.CancelRequest.WatchId)
  197. default:
  198. panic("not implemented")
  199. }
  200. }
  201. }
  202. func (wps *watchProxyStream) sendLoop() {
  203. for {
  204. select {
  205. case wresp, ok := <-wps.watchCh:
  206. if !ok {
  207. return
  208. }
  209. if err := wps.stream.Send(wresp); err != nil {
  210. return
  211. }
  212. case <-wps.ctx.Done():
  213. return
  214. }
  215. }
  216. }
  217. func (wps *watchProxyStream) delete(id int64) {
  218. wps.mu.Lock()
  219. defer wps.mu.Unlock()
  220. w, ok := wps.watchers[id]
  221. if !ok {
  222. return
  223. }
  224. wps.ranges.delete(w)
  225. delete(wps.watchers, id)
  226. resp := &pb.WatchResponse{
  227. Header: &w.lastHeader,
  228. WatchId: id,
  229. Canceled: true,
  230. }
  231. wps.watchCh <- resp
  232. }