watch.go 15 KB

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