watch.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // Copyright 2015 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 v3rpc
  15. import (
  16. "io"
  17. "sync"
  18. "time"
  19. "golang.org/x/net/context"
  20. "github.com/coreos/etcd/etcdserver"
  21. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  22. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/mvcc"
  24. "github.com/coreos/etcd/mvcc/mvccpb"
  25. )
  26. type watchServer struct {
  27. clusterID int64
  28. memberID int64
  29. raftTimer etcdserver.RaftTimer
  30. watchable mvcc.WatchableKV
  31. }
  32. func NewWatchServer(s *etcdserver.EtcdServer) pb.WatchServer {
  33. return &watchServer{
  34. clusterID: int64(s.Cluster().ID()),
  35. memberID: int64(s.ID()),
  36. raftTimer: s,
  37. watchable: s.Watchable(),
  38. }
  39. }
  40. var (
  41. // External test can read this with GetProgressReportInterval()
  42. // and change this to a small value to finish fast with
  43. // SetProgressReportInterval().
  44. progressReportInterval = 10 * time.Minute
  45. progressReportIntervalMu sync.RWMutex
  46. )
  47. func GetProgressReportInterval() time.Duration {
  48. progressReportIntervalMu.RLock()
  49. defer progressReportIntervalMu.RUnlock()
  50. return progressReportInterval
  51. }
  52. func SetProgressReportInterval(newTimeout time.Duration) {
  53. progressReportIntervalMu.Lock()
  54. defer progressReportIntervalMu.Unlock()
  55. progressReportInterval = newTimeout
  56. }
  57. const (
  58. // We send ctrl response inside the read loop. We do not want
  59. // send to block read, but we still want ctrl response we sent to
  60. // be serialized. Thus we use a buffered chan to solve the problem.
  61. // A small buffer should be OK for most cases, since we expect the
  62. // ctrl requests are infrequent.
  63. ctrlStreamBufLen = 16
  64. )
  65. // serverWatchStream is an etcd server side stream. It receives requests
  66. // from client side gRPC stream. It receives watch events from mvcc.WatchStream,
  67. // and creates responses that forwarded to gRPC stream.
  68. // It also forwards control message like watch created and canceled.
  69. type serverWatchStream struct {
  70. clusterID int64
  71. memberID int64
  72. raftTimer etcdserver.RaftTimer
  73. watchable mvcc.WatchableKV
  74. gRPCStream pb.Watch_WatchServer
  75. watchStream mvcc.WatchStream
  76. ctrlStream chan *pb.WatchResponse
  77. // mu protects progress, prevKV
  78. mu sync.Mutex
  79. // progress tracks the watchID that stream might need to send
  80. // progress to.
  81. // TODO: combine progress and prevKV into a single struct?
  82. progress map[mvcc.WatchID]bool
  83. prevKV map[mvcc.WatchID]bool
  84. // closec indicates the stream is closed.
  85. closec chan struct{}
  86. // wg waits for the send loop to complete
  87. wg sync.WaitGroup
  88. }
  89. func (ws *watchServer) Watch(stream pb.Watch_WatchServer) (err error) {
  90. sws := serverWatchStream{
  91. clusterID: ws.clusterID,
  92. memberID: ws.memberID,
  93. raftTimer: ws.raftTimer,
  94. watchable: ws.watchable,
  95. gRPCStream: stream,
  96. watchStream: ws.watchable.NewWatchStream(),
  97. // chan for sending control response like watcher created and canceled.
  98. ctrlStream: make(chan *pb.WatchResponse, ctrlStreamBufLen),
  99. progress: make(map[mvcc.WatchID]bool),
  100. prevKV: make(map[mvcc.WatchID]bool),
  101. closec: make(chan struct{}),
  102. }
  103. sws.wg.Add(1)
  104. go func() {
  105. sws.sendLoop()
  106. sws.wg.Done()
  107. }()
  108. errc := make(chan error, 1)
  109. // Ideally recvLoop would also use sws.wg to signal its completion
  110. // but when stream.Context().Done() is closed, the stream's recv
  111. // may continue to block since it uses a different context, leading to
  112. // deadlock when calling sws.close().
  113. go func() {
  114. if rerr := sws.recvLoop(); rerr != nil {
  115. errc <- rerr
  116. }
  117. }()
  118. select {
  119. case err = <-errc:
  120. close(sws.ctrlStream)
  121. case <-stream.Context().Done():
  122. err = stream.Context().Err()
  123. // the only server-side cancellation is noleader for now.
  124. if err == context.Canceled {
  125. err = rpctypes.ErrGRPCNoLeader
  126. }
  127. }
  128. sws.close()
  129. return err
  130. }
  131. func (sws *serverWatchStream) recvLoop() error {
  132. for {
  133. req, err := sws.gRPCStream.Recv()
  134. if err == io.EOF {
  135. return nil
  136. }
  137. if err != nil {
  138. return err
  139. }
  140. switch uv := req.RequestUnion.(type) {
  141. case *pb.WatchRequest_CreateRequest:
  142. if uv.CreateRequest == nil {
  143. break
  144. }
  145. creq := uv.CreateRequest
  146. if len(creq.Key) == 0 {
  147. // \x00 is the smallest key
  148. creq.Key = []byte{0}
  149. }
  150. if len(creq.RangeEnd) == 1 && creq.RangeEnd[0] == 0 {
  151. // support >= key queries
  152. creq.RangeEnd = []byte{}
  153. }
  154. filters := FiltersFromRequest(creq)
  155. wsrev := sws.watchStream.Rev()
  156. rev := creq.StartRevision
  157. if rev == 0 {
  158. rev = wsrev + 1
  159. }
  160. id := sws.watchStream.Watch(creq.Key, creq.RangeEnd, rev, filters...)
  161. if id != -1 {
  162. sws.mu.Lock()
  163. if creq.ProgressNotify {
  164. sws.progress[id] = true
  165. }
  166. if creq.PrevKv {
  167. sws.prevKV[id] = true
  168. }
  169. sws.mu.Unlock()
  170. }
  171. wr := &pb.WatchResponse{
  172. Header: sws.newResponseHeader(wsrev),
  173. WatchId: int64(id),
  174. Created: true,
  175. Canceled: id == -1,
  176. }
  177. select {
  178. case sws.ctrlStream <- wr:
  179. case <-sws.closec:
  180. return nil
  181. }
  182. case *pb.WatchRequest_CancelRequest:
  183. if uv.CancelRequest != nil {
  184. id := uv.CancelRequest.WatchId
  185. err := sws.watchStream.Cancel(mvcc.WatchID(id))
  186. if err == nil {
  187. sws.ctrlStream <- &pb.WatchResponse{
  188. Header: sws.newResponseHeader(sws.watchStream.Rev()),
  189. WatchId: id,
  190. Canceled: true,
  191. }
  192. sws.mu.Lock()
  193. delete(sws.progress, mvcc.WatchID(id))
  194. delete(sws.prevKV, mvcc.WatchID(id))
  195. sws.mu.Unlock()
  196. }
  197. }
  198. default:
  199. // we probably should not shutdown the entire stream when
  200. // receive an valid command.
  201. // so just do nothing instead.
  202. continue
  203. }
  204. }
  205. }
  206. func (sws *serverWatchStream) sendLoop() {
  207. // watch ids that are currently active
  208. ids := make(map[mvcc.WatchID]struct{})
  209. // watch responses pending on a watch id creation message
  210. pending := make(map[mvcc.WatchID][]*pb.WatchResponse)
  211. interval := GetProgressReportInterval()
  212. progressTicker := time.NewTicker(interval)
  213. defer func() {
  214. progressTicker.Stop()
  215. // drain the chan to clean up pending events
  216. for ws := range sws.watchStream.Chan() {
  217. mvcc.ReportEventReceived(len(ws.Events))
  218. }
  219. for _, wrs := range pending {
  220. for _, ws := range wrs {
  221. mvcc.ReportEventReceived(len(ws.Events))
  222. }
  223. }
  224. }()
  225. for {
  226. select {
  227. case wresp, ok := <-sws.watchStream.Chan():
  228. if !ok {
  229. return
  230. }
  231. // TODO: evs is []mvccpb.Event type
  232. // either return []*mvccpb.Event from the mvcc package
  233. // or define protocol buffer with []mvccpb.Event.
  234. evs := wresp.Events
  235. events := make([]*mvccpb.Event, len(evs))
  236. sws.mu.Lock()
  237. needPrevKV := sws.prevKV[wresp.WatchID]
  238. sws.mu.Unlock()
  239. for i := range evs {
  240. events[i] = &evs[i]
  241. if needPrevKV {
  242. opt := mvcc.RangeOptions{Rev: evs[i].Kv.ModRevision - 1}
  243. r, err := sws.watchable.Range(evs[i].Kv.Key, nil, opt)
  244. if err == nil && len(r.KVs) != 0 {
  245. events[i].PrevKv = &(r.KVs[0])
  246. }
  247. }
  248. }
  249. wr := &pb.WatchResponse{
  250. Header: sws.newResponseHeader(wresp.Revision),
  251. WatchId: int64(wresp.WatchID),
  252. Events: events,
  253. CompactRevision: wresp.CompactRevision,
  254. }
  255. if _, hasId := ids[wresp.WatchID]; !hasId {
  256. // buffer if id not yet announced
  257. wrs := append(pending[wresp.WatchID], wr)
  258. pending[wresp.WatchID] = wrs
  259. continue
  260. }
  261. mvcc.ReportEventReceived(len(evs))
  262. if err := sws.gRPCStream.Send(wr); err != nil {
  263. return
  264. }
  265. sws.mu.Lock()
  266. if len(evs) > 0 && sws.progress[wresp.WatchID] {
  267. // elide next progress update if sent a key update
  268. sws.progress[wresp.WatchID] = false
  269. }
  270. sws.mu.Unlock()
  271. case c, ok := <-sws.ctrlStream:
  272. if !ok {
  273. return
  274. }
  275. if err := sws.gRPCStream.Send(c); err != nil {
  276. return
  277. }
  278. // track id creation
  279. wid := mvcc.WatchID(c.WatchId)
  280. if c.Canceled {
  281. delete(ids, wid)
  282. continue
  283. }
  284. if c.Created {
  285. // flush buffered events
  286. ids[wid] = struct{}{}
  287. for _, v := range pending[wid] {
  288. mvcc.ReportEventReceived(len(v.Events))
  289. if err := sws.gRPCStream.Send(v); err != nil {
  290. return
  291. }
  292. }
  293. delete(pending, wid)
  294. }
  295. case <-progressTicker.C:
  296. sws.mu.Lock()
  297. for id, ok := range sws.progress {
  298. if ok {
  299. sws.watchStream.RequestProgress(id)
  300. }
  301. sws.progress[id] = true
  302. }
  303. sws.mu.Unlock()
  304. case <-sws.closec:
  305. return
  306. }
  307. }
  308. }
  309. func (sws *serverWatchStream) close() {
  310. sws.watchStream.Close()
  311. close(sws.closec)
  312. sws.wg.Wait()
  313. }
  314. func (sws *serverWatchStream) newResponseHeader(rev int64) *pb.ResponseHeader {
  315. return &pb.ResponseHeader{
  316. ClusterId: uint64(sws.clusterID),
  317. MemberId: uint64(sws.memberID),
  318. Revision: rev,
  319. RaftTerm: sws.raftTimer.Term(),
  320. }
  321. }
  322. func filterNoDelete(e mvccpb.Event) bool {
  323. return e.Type == mvccpb.DELETE
  324. }
  325. func filterNoPut(e mvccpb.Event) bool {
  326. return e.Type == mvccpb.PUT
  327. }
  328. func FiltersFromRequest(creq *pb.WatchCreateRequest) []mvcc.FilterFunc {
  329. filters := make([]mvcc.FilterFunc, 0, len(creq.Filters))
  330. for _, ft := range creq.Filters {
  331. switch ft {
  332. case pb.WatchCreateRequest_NOPUT:
  333. filters = append(filters, filterNoPut)
  334. case pb.WatchCreateRequest_NODELETE:
  335. filters = append(filters, filterNoDelete)
  336. default:
  337. }
  338. }
  339. return filters
  340. }