watch.go 11 KB

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