watch.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. sid := wp.nextStreamID
  51. wp.mu.Unlock()
  52. sws := serverWatchStream{
  53. cw: wp.cw,
  54. groups: &wp.wgs,
  55. singles: make(map[int64]*watcherSingle),
  56. inGroups: make(map[int64]struct{}),
  57. id: sid,
  58. gRPCStream: stream,
  59. watchCh: make(chan *pb.WatchResponse, 1024),
  60. proxyCtx: wp.ctx,
  61. }
  62. go sws.recvLoop()
  63. sws.sendLoop()
  64. return wp.ctx.Err()
  65. }
  66. type serverWatchStream struct {
  67. id int64
  68. cw clientv3.Watcher
  69. mu sync.Mutex // make sure any access of groups and singles is atomic
  70. groups *watchergroups
  71. singles map[int64]*watcherSingle
  72. inGroups map[int64]struct{}
  73. gRPCStream pb.Watch_WatchServer
  74. watchCh chan *pb.WatchResponse
  75. nextWatcherID int64
  76. proxyCtx context.Context
  77. }
  78. func (sws *serverWatchStream) close() {
  79. var wg sync.WaitGroup
  80. sws.mu.Lock()
  81. wg.Add(len(sws.singles) + len(sws.inGroups))
  82. for _, ws := range sws.singles {
  83. // copy the range variable to avoid race
  84. copyws := ws
  85. go func() {
  86. copyws.stop()
  87. wg.Done()
  88. }()
  89. }
  90. for id := range sws.inGroups {
  91. // copy the range variable to avoid race
  92. wid := id
  93. go func() {
  94. sws.groups.removeWatcher(receiverID{streamID: sws.id, watcherID: wid})
  95. wg.Done()
  96. }()
  97. }
  98. sws.inGroups = nil
  99. sws.mu.Unlock()
  100. wg.Wait()
  101. close(sws.watchCh)
  102. }
  103. func (sws *serverWatchStream) recvLoop() error {
  104. defer sws.close()
  105. for {
  106. req, err := sws.gRPCStream.Recv()
  107. if err == io.EOF {
  108. return nil
  109. }
  110. if err != nil {
  111. return err
  112. }
  113. switch uv := req.RequestUnion.(type) {
  114. case *pb.WatchRequest_CreateRequest:
  115. cr := uv.CreateRequest
  116. watcher := watcher{
  117. wr: watchRange{
  118. key: string(cr.Key),
  119. end: string(cr.RangeEnd),
  120. },
  121. id: sws.nextWatcherID,
  122. ch: sws.watchCh,
  123. progress: cr.ProgressNotify,
  124. filters: v3rpc.FiltersFromRequest(cr),
  125. }
  126. if cr.StartRevision != 0 {
  127. sws.addDedicatedWatcher(watcher, cr.StartRevision)
  128. } else {
  129. sws.addCoalescedWatcher(watcher)
  130. }
  131. sws.nextWatcherID++
  132. case *pb.WatchRequest_CancelRequest:
  133. sws.removeWatcher(uv.CancelRequest.WatchId)
  134. default:
  135. panic("not implemented")
  136. }
  137. }
  138. }
  139. func (sws *serverWatchStream) sendLoop() {
  140. for {
  141. select {
  142. case wresp, ok := <-sws.watchCh:
  143. if !ok {
  144. return
  145. }
  146. if err := sws.gRPCStream.Send(wresp); err != nil {
  147. return
  148. }
  149. case <-sws.proxyCtx.Done():
  150. return
  151. }
  152. }
  153. }
  154. func (sws *serverWatchStream) addCoalescedWatcher(w watcher) {
  155. sws.mu.Lock()
  156. defer sws.mu.Unlock()
  157. rid := receiverID{streamID: sws.id, watcherID: w.id}
  158. sws.groups.addWatcher(rid, w)
  159. sws.inGroups[w.id] = struct{}{}
  160. }
  161. func (sws *serverWatchStream) addDedicatedWatcher(w watcher, rev int64) {
  162. sws.mu.Lock()
  163. defer sws.mu.Unlock()
  164. ctx, cancel := context.WithCancel(sws.proxyCtx)
  165. wch := sws.cw.Watch(ctx,
  166. w.wr.key, clientv3.WithRange(w.wr.end),
  167. clientv3.WithRev(rev),
  168. clientv3.WithProgressNotify(),
  169. clientv3.WithCreatedNotify(),
  170. )
  171. ws := newWatcherSingle(wch, cancel, w, sws)
  172. sws.singles[w.id] = ws
  173. go ws.run()
  174. }
  175. func (sws *serverWatchStream) maybeCoalesceWatcher(ws watcherSingle) bool {
  176. sws.mu.Lock()
  177. defer sws.mu.Unlock()
  178. rid := receiverID{streamID: sws.id, watcherID: ws.w.id}
  179. // do not add new watchers when stream is closing
  180. if sws.inGroups == nil {
  181. return false
  182. }
  183. if sws.groups.maybeJoinWatcherSingle(rid, ws) {
  184. delete(sws.singles, ws.w.id)
  185. sws.inGroups[ws.w.id] = struct{}{}
  186. return true
  187. }
  188. return false
  189. }
  190. func (sws *serverWatchStream) removeWatcher(id int64) {
  191. sws.mu.Lock()
  192. defer sws.mu.Unlock()
  193. var (
  194. rev int64
  195. ok bool
  196. )
  197. defer func() {
  198. if !ok {
  199. return
  200. }
  201. resp := &pb.WatchResponse{
  202. Header: &pb.ResponseHeader{
  203. // todo: fill in ClusterId
  204. // todo: fill in MemberId:
  205. Revision: rev,
  206. // todo: fill in RaftTerm:
  207. },
  208. WatchId: id,
  209. Canceled: true,
  210. }
  211. sws.watchCh <- resp
  212. }()
  213. rev, ok = sws.groups.removeWatcher(receiverID{streamID: sws.id, watcherID: id})
  214. if ok {
  215. delete(sws.inGroups, id)
  216. return
  217. }
  218. var ws *watcherSingle
  219. if ws, ok = sws.singles[id]; ok {
  220. delete(sws.singles, id)
  221. ws.stop()
  222. rev = ws.lastStoreRev
  223. }
  224. }