watch.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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 clientv3
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "sync"
  20. "time"
  21. v3rpc "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  22. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  23. mvccpb "go.etcd.io/etcd/mvcc/mvccpb"
  24. "google.golang.org/grpc"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/metadata"
  27. "google.golang.org/grpc/status"
  28. )
  29. const (
  30. EventTypeDelete = mvccpb.DELETE
  31. EventTypePut = mvccpb.PUT
  32. closeSendErrTimeout = 250 * time.Millisecond
  33. )
  34. type Event mvccpb.Event
  35. type WatchChan <-chan WatchResponse
  36. type Watcher interface {
  37. // Watch watches on a key or prefix. The watched events will be returned
  38. // through the returned channel. If revisions waiting to be sent over the
  39. // watch are compacted, then the watch will be canceled by the server, the
  40. // client will post a compacted error watch response, and the channel will close.
  41. // If the context "ctx" is canceled or timed out, returned "WatchChan" is closed,
  42. // and "WatchResponse" from this closed channel has zero events and nil "Err()".
  43. // The context "ctx" MUST be canceled, as soon as watcher is no longer being used,
  44. // to release the associated resources.
  45. //
  46. // If the context is "context.Background/TODO", returned "WatchChan" will
  47. // not be closed and block until event is triggered, except when server
  48. // returns a non-recoverable error (e.g. ErrCompacted).
  49. // For example, when context passed with "WithRequireLeader" and the
  50. // connected server has no leader (e.g. due to network partition),
  51. // error "etcdserver: no leader" (ErrNoLeader) will be returned,
  52. // and then "WatchChan" is closed with non-nil "Err()".
  53. // In order to prevent a watch stream being stuck in a partitioned node,
  54. // make sure to wrap context with "WithRequireLeader".
  55. //
  56. // Otherwise, as long as the context has not been canceled or timed out,
  57. // watch will retry on other recoverable errors forever until reconnected.
  58. //
  59. // TODO: explicitly set context error in the last "WatchResponse" message and close channel?
  60. // Currently, client contexts are overwritten with "valCtx" that never closes.
  61. // TODO(v3.4): configure watch retry policy, limit maximum retry number
  62. // (see https://github.com/etcd-io/etcd/issues/8980)
  63. Watch(ctx context.Context, key string, opts ...OpOption) WatchChan
  64. // RequestProgress requests a progress notify response be sent in all watch channels.
  65. RequestProgress(ctx context.Context) error
  66. // Close closes the watcher and cancels all watch requests.
  67. Close() error
  68. }
  69. type WatchResponse struct {
  70. Header pb.ResponseHeader
  71. Events []*Event
  72. // CompactRevision is the minimum revision the watcher may receive.
  73. CompactRevision int64
  74. // Canceled is used to indicate watch failure.
  75. // If the watch failed and the stream was about to close, before the channel is closed,
  76. // the channel sends a final response that has Canceled set to true with a non-nil Err().
  77. Canceled bool
  78. // Created is used to indicate the creation of the watcher.
  79. Created bool
  80. closeErr error
  81. // cancelReason is a reason of canceling watch
  82. cancelReason string
  83. }
  84. // IsCreate returns true if the event tells that the key is newly created.
  85. func (e *Event) IsCreate() bool {
  86. return e.Type == EventTypePut && e.Kv.CreateRevision == e.Kv.ModRevision
  87. }
  88. // IsModify returns true if the event tells that a new value is put on existing key.
  89. func (e *Event) IsModify() bool {
  90. return e.Type == EventTypePut && e.Kv.CreateRevision != e.Kv.ModRevision
  91. }
  92. // Err is the error value if this WatchResponse holds an error.
  93. func (wr *WatchResponse) Err() error {
  94. switch {
  95. case wr.closeErr != nil:
  96. return v3rpc.Error(wr.closeErr)
  97. case wr.CompactRevision != 0:
  98. return v3rpc.ErrCompacted
  99. case wr.Canceled:
  100. if len(wr.cancelReason) != 0 {
  101. return v3rpc.Error(status.Error(codes.FailedPrecondition, wr.cancelReason))
  102. }
  103. return v3rpc.ErrFutureRev
  104. }
  105. return nil
  106. }
  107. // IsProgressNotify returns true if the WatchResponse is progress notification.
  108. func (wr *WatchResponse) IsProgressNotify() bool {
  109. return len(wr.Events) == 0 && !wr.Canceled && !wr.Created && wr.CompactRevision == 0 && wr.Header.Revision != 0
  110. }
  111. // watcher implements the Watcher interface
  112. type watcher struct {
  113. remote pb.WatchClient
  114. callOpts []grpc.CallOption
  115. // mu protects the grpc streams map
  116. mu sync.RWMutex
  117. // streams holds all the active grpc streams keyed by ctx value.
  118. streams map[string]*watchGrpcStream
  119. }
  120. // watchGrpcStream tracks all watch resources attached to a single grpc stream.
  121. type watchGrpcStream struct {
  122. owner *watcher
  123. remote pb.WatchClient
  124. callOpts []grpc.CallOption
  125. // ctx controls internal remote.Watch requests
  126. ctx context.Context
  127. // ctxKey is the key used when looking up this stream's context
  128. ctxKey string
  129. cancel context.CancelFunc
  130. // substreams holds all active watchers on this grpc stream
  131. substreams map[int64]*watcherStream
  132. // resuming holds all resuming watchers on this grpc stream
  133. resuming []*watcherStream
  134. // reqc sends a watch request from Watch() to the main goroutine
  135. reqc chan watchStreamRequest
  136. // respc receives data from the watch client
  137. respc chan *pb.WatchResponse
  138. // donec closes to broadcast shutdown
  139. donec chan struct{}
  140. // errc transmits errors from grpc Recv to the watch stream reconnect logic
  141. errc chan error
  142. // closingc gets the watcherStream of closing watchers
  143. closingc chan *watcherStream
  144. // wg is Done when all substream goroutines have exited
  145. wg sync.WaitGroup
  146. // resumec closes to signal that all substreams should begin resuming
  147. resumec chan struct{}
  148. // closeErr is the error that closed the watch stream
  149. closeErr error
  150. }
  151. // watchStreamRequest is a union of the supported watch request operation types
  152. type watchStreamRequest interface {
  153. toPB() *pb.WatchRequest
  154. }
  155. // watchRequest is issued by the subscriber to start a new watcher
  156. type watchRequest struct {
  157. ctx context.Context
  158. key string
  159. end string
  160. rev int64
  161. // send created notification event if this field is true
  162. createdNotify bool
  163. // progressNotify is for progress updates
  164. progressNotify bool
  165. // fragmentation should be disabled by default
  166. // if true, split watch events when total exceeds
  167. // "--max-request-bytes" flag value + 512-byte
  168. fragment bool
  169. // filters is the list of events to filter out
  170. filters []pb.WatchCreateRequest_FilterType
  171. // get the previous key-value pair before the event happens
  172. prevKV bool
  173. // retc receives a chan WatchResponse once the watcher is established
  174. retc chan chan WatchResponse
  175. }
  176. // progressRequest is issued by the subscriber to request watch progress
  177. type progressRequest struct {
  178. }
  179. // watcherStream represents a registered watcher
  180. type watcherStream struct {
  181. // initReq is the request that initiated this request
  182. initReq watchRequest
  183. // outc publishes watch responses to subscriber
  184. outc chan WatchResponse
  185. // recvc buffers watch responses before publishing
  186. recvc chan *WatchResponse
  187. // donec closes when the watcherStream goroutine stops.
  188. donec chan struct{}
  189. // closing is set to true when stream should be scheduled to shutdown.
  190. closing bool
  191. // id is the registered watch id on the grpc stream
  192. id int64
  193. // buf holds all events received from etcd but not yet consumed by the client
  194. buf []*WatchResponse
  195. }
  196. func NewWatcher(c *Client) Watcher {
  197. return NewWatchFromWatchClient(pb.NewWatchClient(c.conn), c)
  198. }
  199. func NewWatchFromWatchClient(wc pb.WatchClient, c *Client) Watcher {
  200. w := &watcher{
  201. remote: wc,
  202. streams: make(map[string]*watchGrpcStream),
  203. }
  204. if c != nil {
  205. w.callOpts = c.callOpts
  206. }
  207. return w
  208. }
  209. // never closes
  210. var valCtxCh = make(chan struct{})
  211. var zeroTime = time.Unix(0, 0)
  212. // ctx with only the values; never Done
  213. type valCtx struct{ context.Context }
  214. func (vc *valCtx) Deadline() (time.Time, bool) { return zeroTime, false }
  215. func (vc *valCtx) Done() <-chan struct{} { return valCtxCh }
  216. func (vc *valCtx) Err() error { return nil }
  217. func (w *watcher) newWatcherGrpcStream(inctx context.Context) *watchGrpcStream {
  218. ctx, cancel := context.WithCancel(&valCtx{inctx})
  219. wgs := &watchGrpcStream{
  220. owner: w,
  221. remote: w.remote,
  222. callOpts: w.callOpts,
  223. ctx: ctx,
  224. ctxKey: streamKeyFromCtx(inctx),
  225. cancel: cancel,
  226. substreams: make(map[int64]*watcherStream),
  227. respc: make(chan *pb.WatchResponse),
  228. reqc: make(chan watchStreamRequest),
  229. donec: make(chan struct{}),
  230. errc: make(chan error, 1),
  231. closingc: make(chan *watcherStream),
  232. resumec: make(chan struct{}),
  233. }
  234. go wgs.run()
  235. return wgs
  236. }
  237. // Watch posts a watch request to run() and waits for a new watcher channel
  238. func (w *watcher) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan {
  239. ow := opWatch(key, opts...)
  240. var filters []pb.WatchCreateRequest_FilterType
  241. if ow.filterPut {
  242. filters = append(filters, pb.WatchCreateRequest_NOPUT)
  243. }
  244. if ow.filterDelete {
  245. filters = append(filters, pb.WatchCreateRequest_NODELETE)
  246. }
  247. wr := &watchRequest{
  248. ctx: ctx,
  249. createdNotify: ow.createdNotify,
  250. key: string(ow.key),
  251. end: string(ow.end),
  252. rev: ow.rev,
  253. progressNotify: ow.progressNotify,
  254. fragment: ow.fragment,
  255. filters: filters,
  256. prevKV: ow.prevKV,
  257. retc: make(chan chan WatchResponse, 1),
  258. }
  259. ok := false
  260. ctxKey := streamKeyFromCtx(ctx)
  261. // find or allocate appropriate grpc watch stream
  262. w.mu.Lock()
  263. if w.streams == nil {
  264. // closed
  265. w.mu.Unlock()
  266. ch := make(chan WatchResponse)
  267. close(ch)
  268. return ch
  269. }
  270. wgs := w.streams[ctxKey]
  271. if wgs == nil {
  272. wgs = w.newWatcherGrpcStream(ctx)
  273. w.streams[ctxKey] = wgs
  274. }
  275. donec := wgs.donec
  276. reqc := wgs.reqc
  277. w.mu.Unlock()
  278. // couldn't create channel; return closed channel
  279. closeCh := make(chan WatchResponse, 1)
  280. // submit request
  281. select {
  282. case reqc <- wr:
  283. ok = true
  284. case <-wr.ctx.Done():
  285. case <-donec:
  286. if wgs.closeErr != nil {
  287. closeCh <- WatchResponse{Canceled: true, closeErr: wgs.closeErr}
  288. break
  289. }
  290. // retry; may have dropped stream from no ctxs
  291. return w.Watch(ctx, key, opts...)
  292. }
  293. // receive channel
  294. if ok {
  295. select {
  296. case ret := <-wr.retc:
  297. return ret
  298. case <-ctx.Done():
  299. case <-donec:
  300. if wgs.closeErr != nil {
  301. closeCh <- WatchResponse{Canceled: true, closeErr: wgs.closeErr}
  302. break
  303. }
  304. // retry; may have dropped stream from no ctxs
  305. return w.Watch(ctx, key, opts...)
  306. }
  307. }
  308. close(closeCh)
  309. return closeCh
  310. }
  311. func (w *watcher) Close() (err error) {
  312. w.mu.Lock()
  313. streams := w.streams
  314. w.streams = nil
  315. w.mu.Unlock()
  316. for _, wgs := range streams {
  317. if werr := wgs.close(); werr != nil {
  318. err = werr
  319. }
  320. }
  321. // Consider context.Canceled as a successful close
  322. if err == context.Canceled {
  323. err = nil
  324. }
  325. return err
  326. }
  327. // RequestProgress requests a progress notify response be sent in all watch channels.
  328. func (w *watcher) RequestProgress(ctx context.Context) (err error) {
  329. ctxKey := streamKeyFromCtx(ctx)
  330. w.mu.Lock()
  331. if w.streams == nil {
  332. return fmt.Errorf("no stream found for context")
  333. }
  334. wgs := w.streams[ctxKey]
  335. if wgs == nil {
  336. wgs = w.newWatcherGrpcStream(ctx)
  337. w.streams[ctxKey] = wgs
  338. }
  339. donec := wgs.donec
  340. reqc := wgs.reqc
  341. w.mu.Unlock()
  342. pr := &progressRequest{}
  343. select {
  344. case reqc <- pr:
  345. return nil
  346. case <-ctx.Done():
  347. if err == nil {
  348. return ctx.Err()
  349. }
  350. return err
  351. case <-donec:
  352. if wgs.closeErr != nil {
  353. return wgs.closeErr
  354. }
  355. // retry; may have dropped stream from no ctxs
  356. return w.RequestProgress(ctx)
  357. }
  358. }
  359. func (w *watchGrpcStream) close() (err error) {
  360. w.cancel()
  361. <-w.donec
  362. select {
  363. case err = <-w.errc:
  364. default:
  365. }
  366. return toErr(w.ctx, err)
  367. }
  368. func (w *watcher) closeStream(wgs *watchGrpcStream) {
  369. w.mu.Lock()
  370. close(wgs.donec)
  371. wgs.cancel()
  372. if w.streams != nil {
  373. delete(w.streams, wgs.ctxKey)
  374. }
  375. w.mu.Unlock()
  376. }
  377. func (w *watchGrpcStream) addSubstream(resp *pb.WatchResponse, ws *watcherStream) {
  378. // check watch ID for backward compatibility (<= v3.3)
  379. if resp.WatchId == -1 || (resp.Canceled && resp.CancelReason != "") {
  380. w.closeErr = v3rpc.Error(errors.New(resp.CancelReason))
  381. // failed; no channel
  382. close(ws.recvc)
  383. return
  384. }
  385. ws.id = resp.WatchId
  386. w.substreams[ws.id] = ws
  387. }
  388. func (w *watchGrpcStream) sendCloseSubstream(ws *watcherStream, resp *WatchResponse) {
  389. select {
  390. case ws.outc <- *resp:
  391. case <-ws.initReq.ctx.Done():
  392. case <-time.After(closeSendErrTimeout):
  393. }
  394. close(ws.outc)
  395. }
  396. func (w *watchGrpcStream) closeSubstream(ws *watcherStream) {
  397. // send channel response in case stream was never established
  398. select {
  399. case ws.initReq.retc <- ws.outc:
  400. default:
  401. }
  402. // close subscriber's channel
  403. if closeErr := w.closeErr; closeErr != nil && ws.initReq.ctx.Err() == nil {
  404. go w.sendCloseSubstream(ws, &WatchResponse{Canceled: true, closeErr: w.closeErr})
  405. } else if ws.outc != nil {
  406. close(ws.outc)
  407. }
  408. if ws.id != -1 {
  409. delete(w.substreams, ws.id)
  410. return
  411. }
  412. for i := range w.resuming {
  413. if w.resuming[i] == ws {
  414. w.resuming[i] = nil
  415. return
  416. }
  417. }
  418. }
  419. // run is the root of the goroutines for managing a watcher client
  420. func (w *watchGrpcStream) run() {
  421. var wc pb.Watch_WatchClient
  422. var closeErr error
  423. // substreams marked to close but goroutine still running; needed for
  424. // avoiding double-closing recvc on grpc stream teardown
  425. closing := make(map[*watcherStream]struct{})
  426. defer func() {
  427. w.closeErr = closeErr
  428. // shutdown substreams and resuming substreams
  429. for _, ws := range w.substreams {
  430. if _, ok := closing[ws]; !ok {
  431. close(ws.recvc)
  432. closing[ws] = struct{}{}
  433. }
  434. }
  435. for _, ws := range w.resuming {
  436. if _, ok := closing[ws]; ws != nil && !ok {
  437. close(ws.recvc)
  438. closing[ws] = struct{}{}
  439. }
  440. }
  441. w.joinSubstreams()
  442. for range closing {
  443. w.closeSubstream(<-w.closingc)
  444. }
  445. w.wg.Wait()
  446. w.owner.closeStream(w)
  447. }()
  448. // start a stream with the etcd grpc server
  449. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  450. return
  451. }
  452. cancelSet := make(map[int64]struct{})
  453. var cur *pb.WatchResponse
  454. for {
  455. select {
  456. // Watch() requested
  457. case req := <-w.reqc:
  458. switch wreq := req.(type) {
  459. case *watchRequest:
  460. outc := make(chan WatchResponse, 1)
  461. // TODO: pass custom watch ID?
  462. ws := &watcherStream{
  463. initReq: *wreq,
  464. id: -1,
  465. outc: outc,
  466. // unbuffered so resumes won't cause repeat events
  467. recvc: make(chan *WatchResponse),
  468. }
  469. ws.donec = make(chan struct{})
  470. w.wg.Add(1)
  471. go w.serveSubstream(ws, w.resumec)
  472. // queue up for watcher creation/resume
  473. w.resuming = append(w.resuming, ws)
  474. if len(w.resuming) == 1 {
  475. // head of resume queue, can register a new watcher
  476. wc.Send(ws.initReq.toPB())
  477. }
  478. case *progressRequest:
  479. wc.Send(wreq.toPB())
  480. }
  481. // new events from the watch client
  482. case pbresp := <-w.respc:
  483. if cur == nil || pbresp.Created || pbresp.Canceled {
  484. cur = pbresp
  485. } else if cur != nil && cur.WatchId == pbresp.WatchId {
  486. // merge new events
  487. cur.Events = append(cur.Events, pbresp.Events...)
  488. // update "Fragment" field; last response with "Fragment" == false
  489. cur.Fragment = pbresp.Fragment
  490. }
  491. switch {
  492. case pbresp.Created:
  493. // response to head of queue creation
  494. if ws := w.resuming[0]; ws != nil {
  495. w.addSubstream(pbresp, ws)
  496. w.dispatchEvent(pbresp)
  497. w.resuming[0] = nil
  498. }
  499. if ws := w.nextResume(); ws != nil {
  500. wc.Send(ws.initReq.toPB())
  501. }
  502. // reset for next iteration
  503. cur = nil
  504. case pbresp.Canceled && pbresp.CompactRevision == 0:
  505. delete(cancelSet, pbresp.WatchId)
  506. if ws, ok := w.substreams[pbresp.WatchId]; ok {
  507. // signal to stream goroutine to update closingc
  508. close(ws.recvc)
  509. closing[ws] = struct{}{}
  510. }
  511. // reset for next iteration
  512. cur = nil
  513. case cur.Fragment:
  514. // watch response events are still fragmented
  515. // continue to fetch next fragmented event arrival
  516. continue
  517. default:
  518. // dispatch to appropriate watch stream
  519. ok := w.dispatchEvent(cur)
  520. // reset for next iteration
  521. cur = nil
  522. if ok {
  523. break
  524. }
  525. // watch response on unexpected watch id; cancel id
  526. if _, ok := cancelSet[pbresp.WatchId]; ok {
  527. break
  528. }
  529. cancelSet[pbresp.WatchId] = struct{}{}
  530. cr := &pb.WatchRequest_CancelRequest{
  531. CancelRequest: &pb.WatchCancelRequest{
  532. WatchId: pbresp.WatchId,
  533. },
  534. }
  535. req := &pb.WatchRequest{RequestUnion: cr}
  536. wc.Send(req)
  537. }
  538. // watch client failed on Recv; spawn another if possible
  539. case err := <-w.errc:
  540. if isHaltErr(w.ctx, err) || toErr(w.ctx, err) == v3rpc.ErrNoLeader {
  541. closeErr = err
  542. return
  543. }
  544. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  545. return
  546. }
  547. if ws := w.nextResume(); ws != nil {
  548. wc.Send(ws.initReq.toPB())
  549. }
  550. cancelSet = make(map[int64]struct{})
  551. case <-w.ctx.Done():
  552. return
  553. case ws := <-w.closingc:
  554. w.closeSubstream(ws)
  555. delete(closing, ws)
  556. // no more watchers on this stream, shutdown
  557. if len(w.substreams)+len(w.resuming) == 0 {
  558. return
  559. }
  560. }
  561. }
  562. }
  563. // nextResume chooses the next resuming to register with the grpc stream. Abandoned
  564. // streams are marked as nil in the queue since the head must wait for its inflight registration.
  565. func (w *watchGrpcStream) nextResume() *watcherStream {
  566. for len(w.resuming) != 0 {
  567. if w.resuming[0] != nil {
  568. return w.resuming[0]
  569. }
  570. w.resuming = w.resuming[1:len(w.resuming)]
  571. }
  572. return nil
  573. }
  574. // dispatchEvent sends a WatchResponse to the appropriate watcher stream
  575. func (w *watchGrpcStream) dispatchEvent(pbresp *pb.WatchResponse) bool {
  576. events := make([]*Event, len(pbresp.Events))
  577. for i, ev := range pbresp.Events {
  578. events[i] = (*Event)(ev)
  579. }
  580. // TODO: return watch ID?
  581. wr := &WatchResponse{
  582. Header: *pbresp.Header,
  583. Events: events,
  584. CompactRevision: pbresp.CompactRevision,
  585. Created: pbresp.Created,
  586. Canceled: pbresp.Canceled,
  587. cancelReason: pbresp.CancelReason,
  588. }
  589. // watch IDs are zero indexed, so request notify watch responses are assigned a watch ID of -1 to
  590. // indicate they should be broadcast.
  591. if wr.IsProgressNotify() && pbresp.WatchId == -1 {
  592. return w.broadcastResponse(wr)
  593. }
  594. return w.unicastResponse(wr, pbresp.WatchId)
  595. }
  596. // broadcastResponse send a watch response to all watch substreams.
  597. func (w *watchGrpcStream) broadcastResponse(wr *WatchResponse) bool {
  598. for _, ws := range w.substreams {
  599. select {
  600. case ws.recvc <- wr:
  601. case <-ws.donec:
  602. }
  603. }
  604. return true
  605. }
  606. // unicastResponse sends a watch response to a specific watch substream.
  607. func (w *watchGrpcStream) unicastResponse(wr *WatchResponse, watchId int64) bool {
  608. ws, ok := w.substreams[watchId]
  609. if !ok {
  610. return false
  611. }
  612. select {
  613. case ws.recvc <- wr:
  614. case <-ws.donec:
  615. return false
  616. }
  617. return true
  618. }
  619. // serveWatchClient forwards messages from the grpc stream to run()
  620. func (w *watchGrpcStream) serveWatchClient(wc pb.Watch_WatchClient) {
  621. for {
  622. resp, err := wc.Recv()
  623. if err != nil {
  624. select {
  625. case w.errc <- err:
  626. case <-w.donec:
  627. }
  628. return
  629. }
  630. select {
  631. case w.respc <- resp:
  632. case <-w.donec:
  633. return
  634. }
  635. }
  636. }
  637. // serveSubstream forwards watch responses from run() to the subscriber
  638. func (w *watchGrpcStream) serveSubstream(ws *watcherStream, resumec chan struct{}) {
  639. if ws.closing {
  640. panic("created substream goroutine but substream is closing")
  641. }
  642. // nextRev is the minimum expected next revision
  643. nextRev := ws.initReq.rev
  644. resuming := false
  645. defer func() {
  646. if !resuming {
  647. ws.closing = true
  648. }
  649. close(ws.donec)
  650. if !resuming {
  651. w.closingc <- ws
  652. }
  653. w.wg.Done()
  654. }()
  655. emptyWr := &WatchResponse{}
  656. for {
  657. curWr := emptyWr
  658. outc := ws.outc
  659. if len(ws.buf) > 0 {
  660. curWr = ws.buf[0]
  661. } else {
  662. outc = nil
  663. }
  664. select {
  665. case outc <- *curWr:
  666. if ws.buf[0].Err() != nil {
  667. return
  668. }
  669. ws.buf[0] = nil
  670. ws.buf = ws.buf[1:]
  671. case wr, ok := <-ws.recvc:
  672. if !ok {
  673. // shutdown from closeSubstream
  674. return
  675. }
  676. if wr.Created {
  677. if ws.initReq.retc != nil {
  678. ws.initReq.retc <- ws.outc
  679. // to prevent next write from taking the slot in buffered channel
  680. // and posting duplicate create events
  681. ws.initReq.retc = nil
  682. // send first creation event only if requested
  683. if ws.initReq.createdNotify {
  684. ws.outc <- *wr
  685. }
  686. // once the watch channel is returned, a current revision
  687. // watch must resume at the store revision. This is necessary
  688. // for the following case to work as expected:
  689. // wch := m1.Watch("a")
  690. // m2.Put("a", "b")
  691. // <-wch
  692. // If the revision is only bound on the first observed event,
  693. // if wch is disconnected before the Put is issued, then reconnects
  694. // after it is committed, it'll miss the Put.
  695. if ws.initReq.rev == 0 {
  696. nextRev = wr.Header.Revision
  697. }
  698. }
  699. } else {
  700. // current progress of watch; <= store revision
  701. nextRev = wr.Header.Revision
  702. }
  703. if len(wr.Events) > 0 {
  704. nextRev = wr.Events[len(wr.Events)-1].Kv.ModRevision + 1
  705. }
  706. ws.initReq.rev = nextRev
  707. // created event is already sent above,
  708. // watcher should not post duplicate events
  709. if wr.Created {
  710. continue
  711. }
  712. // TODO pause channel if buffer gets too large
  713. ws.buf = append(ws.buf, wr)
  714. case <-w.ctx.Done():
  715. return
  716. case <-ws.initReq.ctx.Done():
  717. return
  718. case <-resumec:
  719. resuming = true
  720. return
  721. }
  722. }
  723. // lazily send cancel message if events on missing id
  724. }
  725. func (w *watchGrpcStream) newWatchClient() (pb.Watch_WatchClient, error) {
  726. // mark all substreams as resuming
  727. close(w.resumec)
  728. w.resumec = make(chan struct{})
  729. w.joinSubstreams()
  730. for _, ws := range w.substreams {
  731. ws.id = -1
  732. w.resuming = append(w.resuming, ws)
  733. }
  734. // strip out nils, if any
  735. var resuming []*watcherStream
  736. for _, ws := range w.resuming {
  737. if ws != nil {
  738. resuming = append(resuming, ws)
  739. }
  740. }
  741. w.resuming = resuming
  742. w.substreams = make(map[int64]*watcherStream)
  743. // connect to grpc stream while accepting watcher cancelation
  744. stopc := make(chan struct{})
  745. donec := w.waitCancelSubstreams(stopc)
  746. wc, err := w.openWatchClient()
  747. close(stopc)
  748. <-donec
  749. // serve all non-closing streams, even if there's a client error
  750. // so that the teardown path can shutdown the streams as expected.
  751. for _, ws := range w.resuming {
  752. if ws.closing {
  753. continue
  754. }
  755. ws.donec = make(chan struct{})
  756. w.wg.Add(1)
  757. go w.serveSubstream(ws, w.resumec)
  758. }
  759. if err != nil {
  760. return nil, v3rpc.Error(err)
  761. }
  762. // receive data from new grpc stream
  763. go w.serveWatchClient(wc)
  764. return wc, nil
  765. }
  766. func (w *watchGrpcStream) waitCancelSubstreams(stopc <-chan struct{}) <-chan struct{} {
  767. var wg sync.WaitGroup
  768. wg.Add(len(w.resuming))
  769. donec := make(chan struct{})
  770. for i := range w.resuming {
  771. go func(ws *watcherStream) {
  772. defer wg.Done()
  773. if ws.closing {
  774. if ws.initReq.ctx.Err() != nil && ws.outc != nil {
  775. close(ws.outc)
  776. ws.outc = nil
  777. }
  778. return
  779. }
  780. select {
  781. case <-ws.initReq.ctx.Done():
  782. // closed ws will be removed from resuming
  783. ws.closing = true
  784. close(ws.outc)
  785. ws.outc = nil
  786. w.wg.Add(1)
  787. go func() {
  788. defer w.wg.Done()
  789. w.closingc <- ws
  790. }()
  791. case <-stopc:
  792. }
  793. }(w.resuming[i])
  794. }
  795. go func() {
  796. defer close(donec)
  797. wg.Wait()
  798. }()
  799. return donec
  800. }
  801. // joinSubstreams waits for all substream goroutines to complete.
  802. func (w *watchGrpcStream) joinSubstreams() {
  803. for _, ws := range w.substreams {
  804. <-ws.donec
  805. }
  806. for _, ws := range w.resuming {
  807. if ws != nil {
  808. <-ws.donec
  809. }
  810. }
  811. }
  812. var maxBackoff = 100 * time.Millisecond
  813. // openWatchClient retries opening a watch client until success or halt.
  814. // manually retry in case "ws==nil && err==nil"
  815. // TODO: remove FailFast=false
  816. func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
  817. backoff := time.Millisecond
  818. for {
  819. select {
  820. case <-w.ctx.Done():
  821. if err == nil {
  822. return nil, w.ctx.Err()
  823. }
  824. return nil, err
  825. default:
  826. }
  827. if ws, err = w.remote.Watch(w.ctx, w.callOpts...); ws != nil && err == nil {
  828. break
  829. }
  830. if isHaltErr(w.ctx, err) {
  831. return nil, v3rpc.Error(err)
  832. }
  833. if isUnavailableErr(w.ctx, err) {
  834. // retry, but backoff
  835. if backoff < maxBackoff {
  836. // 25% backoff factor
  837. backoff = backoff + backoff/4
  838. if backoff > maxBackoff {
  839. backoff = maxBackoff
  840. }
  841. }
  842. time.Sleep(backoff)
  843. }
  844. }
  845. return ws, nil
  846. }
  847. // toPB converts an internal watch request structure to its protobuf WatchRequest structure.
  848. func (wr *watchRequest) toPB() *pb.WatchRequest {
  849. req := &pb.WatchCreateRequest{
  850. StartRevision: wr.rev,
  851. Key: []byte(wr.key),
  852. RangeEnd: []byte(wr.end),
  853. ProgressNotify: wr.progressNotify,
  854. Filters: wr.filters,
  855. PrevKv: wr.prevKV,
  856. Fragment: wr.fragment,
  857. }
  858. cr := &pb.WatchRequest_CreateRequest{CreateRequest: req}
  859. return &pb.WatchRequest{RequestUnion: cr}
  860. }
  861. // toPB converts an internal progress request structure to its protobuf WatchRequest structure.
  862. func (pr *progressRequest) toPB() *pb.WatchRequest {
  863. req := &pb.WatchProgressRequest{}
  864. cr := &pb.WatchRequest_ProgressRequest{ProgressRequest: req}
  865. return &pb.WatchRequest{RequestUnion: cr}
  866. }
  867. func streamKeyFromCtx(ctx context.Context) string {
  868. if md, ok := metadata.FromOutgoingContext(ctx); ok {
  869. return fmt.Sprintf("%+v", md)
  870. }
  871. return ""
  872. }