watch.go 5.3 KB

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