watch.go 13 KB

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