watch.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. "io"
  17. "sync"
  18. "golang.org/x/net/context"
  19. "github.com/coreos/etcd/clientv3"
  20. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. )
  23. type watchProxy struct {
  24. cw clientv3.Watcher
  25. wgs watchergroups
  26. mu sync.Mutex
  27. nextStreamID int64
  28. ctx context.Context
  29. }
  30. func NewWatchProxy(c *clientv3.Client) pb.WatchServer {
  31. wp := &watchProxy{
  32. cw: c.Watcher,
  33. wgs: watchergroups{
  34. cw: c.Watcher,
  35. groups: make(map[watchRange]*watcherGroup),
  36. idToGroup: make(map[receiverID]*watcherGroup),
  37. proxyCtx: c.Ctx(),
  38. },
  39. ctx: c.Ctx(),
  40. }
  41. go func() {
  42. <-wp.ctx.Done()
  43. wp.wgs.stop()
  44. }()
  45. return wp
  46. }
  47. func (wp *watchProxy) Watch(stream pb.Watch_WatchServer) (err error) {
  48. wp.mu.Lock()
  49. wp.nextStreamID++
  50. wp.mu.Unlock()
  51. sws := serverWatchStream{
  52. cw: wp.cw,
  53. groups: &wp.wgs,
  54. singles: make(map[int64]*watcherSingle),
  55. id: wp.nextStreamID,
  56. gRPCStream: stream,
  57. watchCh: make(chan *pb.WatchResponse, 10),
  58. proxyCtx: wp.ctx,
  59. }
  60. go sws.recvLoop()
  61. sws.sendLoop()
  62. return wp.ctx.Err()
  63. }
  64. type serverWatchStream struct {
  65. id int64
  66. cw clientv3.Watcher
  67. mu sync.Mutex // make sure any access of groups and singles is atomic
  68. groups *watchergroups
  69. singles map[int64]*watcherSingle
  70. gRPCStream pb.Watch_WatchServer
  71. watchCh chan *pb.WatchResponse
  72. nextWatcherID int64
  73. proxyCtx context.Context
  74. }
  75. func (sws *serverWatchStream) close() {
  76. close(sws.watchCh)
  77. var wg sync.WaitGroup
  78. sws.mu.Lock()
  79. wg.Add(len(sws.singles))
  80. for _, ws := range sws.singles {
  81. ws.stop()
  82. // copy the range variable to avoid race
  83. copyws := ws
  84. go func() {
  85. <-copyws.stopNotify()
  86. wg.Done()
  87. }()
  88. }
  89. sws.mu.Unlock()
  90. wg.Wait()
  91. }
  92. func (sws *serverWatchStream) recvLoop() error {
  93. defer sws.close()
  94. for {
  95. req, err := sws.gRPCStream.Recv()
  96. if err == io.EOF {
  97. return nil
  98. }
  99. if err != nil {
  100. return err
  101. }
  102. switch uv := req.RequestUnion.(type) {
  103. case *pb.WatchRequest_CreateRequest:
  104. cr := uv.CreateRequest
  105. watcher := watcher{
  106. wr: watchRange{
  107. key: string(cr.Key),
  108. end: string(cr.RangeEnd),
  109. },
  110. id: sws.nextWatcherID,
  111. ch: sws.watchCh,
  112. progress: cr.ProgressNotify,
  113. filters: v3rpc.FiltersFromRequest(cr),
  114. }
  115. if cr.StartRevision != 0 {
  116. sws.addDedicatedWatcher(watcher, cr.StartRevision)
  117. } else {
  118. sws.addCoalescedWatcher(watcher)
  119. }
  120. sws.nextWatcherID++
  121. case *pb.WatchRequest_CancelRequest:
  122. sws.removeWatcher(uv.CancelRequest.WatchId)
  123. default:
  124. panic("not implemented")
  125. }
  126. }
  127. }
  128. func (sws *serverWatchStream) sendLoop() {
  129. for {
  130. select {
  131. case wresp, ok := <-sws.watchCh:
  132. if !ok {
  133. return
  134. }
  135. if err := sws.gRPCStream.Send(wresp); err != nil {
  136. return
  137. }
  138. case <-sws.proxyCtx.Done():
  139. return
  140. }
  141. }
  142. }
  143. func (sws *serverWatchStream) addCoalescedWatcher(w watcher) {
  144. sws.mu.Lock()
  145. defer sws.mu.Unlock()
  146. rid := receiverID{streamID: sws.id, watcherID: w.id}
  147. sws.groups.addWatcher(rid, w)
  148. }
  149. func (sws *serverWatchStream) addDedicatedWatcher(w watcher, rev int64) {
  150. sws.mu.Lock()
  151. defer sws.mu.Unlock()
  152. ctx, cancel := context.WithCancel(sws.proxyCtx)
  153. wch := sws.cw.Watch(ctx,
  154. w.wr.key, clientv3.WithRange(w.wr.end),
  155. clientv3.WithRev(rev),
  156. clientv3.WithProgressNotify(),
  157. clientv3.WithCreatedNotify(),
  158. )
  159. ws := newWatcherSingle(wch, cancel, w, sws)
  160. sws.singles[w.id] = ws
  161. go ws.run()
  162. }
  163. func (sws *serverWatchStream) maybeCoalesceWatcher(ws watcherSingle) bool {
  164. sws.mu.Lock()
  165. defer sws.mu.Unlock()
  166. rid := receiverID{streamID: sws.id, watcherID: ws.w.id}
  167. if sws.groups.maybeJoinWatcherSingle(rid, ws) {
  168. delete(sws.singles, ws.w.id)
  169. return true
  170. }
  171. return false
  172. }
  173. func (sws *serverWatchStream) removeWatcher(id int64) {
  174. sws.mu.Lock()
  175. defer sws.mu.Unlock()
  176. var (
  177. rev int64
  178. ok bool
  179. )
  180. defer func() {
  181. if !ok {
  182. return
  183. }
  184. resp := &pb.WatchResponse{
  185. Header: &pb.ResponseHeader{
  186. // todo: fill in ClusterId
  187. // todo: fill in MemberId:
  188. Revision: rev,
  189. // todo: fill in RaftTerm:
  190. },
  191. WatchId: id,
  192. Canceled: true,
  193. }
  194. sws.watchCh <- resp
  195. }()
  196. rev, ok = sws.groups.removeWatcher(receiverID{streamID: sws.id, watcherID: id})
  197. if ok {
  198. return
  199. }
  200. var ws *watcherSingle
  201. if ws, ok = sws.singles[id]; ok {
  202. delete(sws.singles, id)
  203. ws.stop()
  204. rev = ws.lastStoreRev
  205. }
  206. }