watch.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. proxyCtx: c.Ctx(),
  37. },
  38. ctx: c.Ctx(),
  39. }
  40. go func() {
  41. <-wp.ctx.Done()
  42. wp.wgs.stop()
  43. }()
  44. return wp
  45. }
  46. func (wp *watchProxy) Watch(stream pb.Watch_WatchServer) (err error) {
  47. wp.mu.Lock()
  48. wp.nextStreamID++
  49. wp.mu.Unlock()
  50. sws := serverWatchStream{
  51. cw: wp.cw,
  52. groups: &wp.wgs,
  53. singles: make(map[int64]*watcherSingle),
  54. id: wp.nextStreamID,
  55. gRPCStream: stream,
  56. ctrlCh: make(chan *pb.WatchResponse, 10),
  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. ctrlCh chan *pb.WatchResponse
  72. watchCh chan *pb.WatchResponse
  73. nextWatcherID int64
  74. proxyCtx context.Context
  75. }
  76. func (sws *serverWatchStream) close() {
  77. close(sws.watchCh)
  78. close(sws.ctrlCh)
  79. var wg sync.WaitGroup
  80. sws.mu.Lock()
  81. wg.Add(len(sws.singles))
  82. for _, ws := range sws.singles {
  83. ws.stop()
  84. // copy the range variable to avoid race
  85. copyws := ws
  86. go func() {
  87. <-copyws.stopNotify()
  88. wg.Done()
  89. }()
  90. }
  91. sws.mu.Unlock()
  92. wg.Wait()
  93. }
  94. func (sws *serverWatchStream) recvLoop() error {
  95. defer sws.close()
  96. for {
  97. req, err := sws.gRPCStream.Recv()
  98. if err == io.EOF {
  99. return nil
  100. }
  101. if err != nil {
  102. return err
  103. }
  104. switch uv := req.RequestUnion.(type) {
  105. case *pb.WatchRequest_CreateRequest:
  106. cr := uv.CreateRequest
  107. watcher := watcher{
  108. wr: watchRange{
  109. key: string(cr.Key),
  110. end: string(cr.RangeEnd),
  111. },
  112. id: sws.nextWatcherID,
  113. ch: sws.watchCh,
  114. progress: cr.ProgressNotify,
  115. filters: v3rpc.FiltersFromRequest(cr),
  116. }
  117. if cr.StartRevision != 0 {
  118. sws.addDedicatedWatcher(watcher, cr.StartRevision)
  119. } else {
  120. sws.addCoalescedWatcher(watcher)
  121. }
  122. sws.nextWatcherID++
  123. case *pb.WatchRequest_CancelRequest:
  124. sws.removeWatcher(uv.CancelRequest.WatchId)
  125. default:
  126. panic("not implemented")
  127. }
  128. }
  129. }
  130. func (sws *serverWatchStream) sendLoop() {
  131. for {
  132. select {
  133. case wresp, ok := <-sws.watchCh:
  134. if !ok {
  135. return
  136. }
  137. if err := sws.gRPCStream.Send(wresp); err != nil {
  138. return
  139. }
  140. case c, ok := <-sws.ctrlCh:
  141. if !ok {
  142. return
  143. }
  144. if err := sws.gRPCStream.Send(c); err != nil {
  145. return
  146. }
  147. case <-sws.proxyCtx.Done():
  148. return
  149. }
  150. }
  151. }
  152. func (sws *serverWatchStream) addCoalescedWatcher(w watcher) {
  153. sws.mu.Lock()
  154. defer sws.mu.Unlock()
  155. rid := receiverID{streamID: sws.id, watcherID: w.id}
  156. sws.groups.addWatcher(rid, w)
  157. }
  158. func (sws *serverWatchStream) addDedicatedWatcher(w watcher, rev int64) {
  159. sws.mu.Lock()
  160. defer sws.mu.Unlock()
  161. ctx, cancel := context.WithCancel(sws.proxyCtx)
  162. wch := sws.cw.Watch(ctx,
  163. w.wr.key, clientv3.WithRange(w.wr.end),
  164. clientv3.WithRev(rev),
  165. clientv3.WithProgressNotify(),
  166. clientv3.WithCreatedNotify(),
  167. )
  168. ws := newWatcherSingle(wch, cancel, w, sws)
  169. sws.singles[w.id] = ws
  170. go ws.run()
  171. }
  172. func (sws *serverWatchStream) maybeCoalesceWatcher(ws watcherSingle) bool {
  173. sws.mu.Lock()
  174. defer sws.mu.Unlock()
  175. rid := receiverID{streamID: sws.id, watcherID: ws.w.id}
  176. if sws.groups.maybeJoinWatcherSingle(rid, ws) {
  177. delete(sws.singles, ws.w.id)
  178. return true
  179. }
  180. return false
  181. }
  182. func (sws *serverWatchStream) removeWatcher(id int64) {
  183. sws.mu.Lock()
  184. defer sws.mu.Unlock()
  185. if sws.groups.removeWatcher(receiverID{streamID: sws.id, watcherID: id}) {
  186. return
  187. }
  188. if ws, ok := sws.singles[id]; ok {
  189. delete(sws.singles, id)
  190. ws.stop()
  191. }
  192. }